日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Count Primes(leetcode204)

發布時間:2025/3/8 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Count Primes(leetcode204) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

Count the number of prime numbers less than a non-negative number,?n.

Example:

Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. //想先用粗暴的方法實現一下 public static int countPrimes(int n) {int count = 0;for(int i = 1;i<n;i++){if(isPrime(i)){count ++;}}return count;}//全部判斷一下是否書素數 但是這看到有是那個循環 時間復雜度接受不了 private static boolean isPrime(int i) {if(i ==1){return false;}for(int j =2;j< i;j++){for(int j2 =2;j2< i;j2++){if(j*j2 == i){return false;}}}return true;}//如果稍微優化一下呢 結果還是超時 public static boolean isPrime2(int i) {if(i ==1 ){return false;}//這樣是否可以快點去掉一些數據if(i > 10 && (i%2==0 ||i%3==0||i%5==0||i%7==0)){return false;}for(int j =2;j< Math.sqrt(i)+1;j++){int j2 = (int)(Math.sqrt(i)) > 2? (int)(Math.sqrt(i)):2;for(; j2< i; j2++){if(j*j2 == i){return false;}}}return true;}/**這里的想法是反一下 找出所有的合數*/ public static int countPrimes2(int n) {boolean[] notPrime = new boolean[n];int count = 0;for (int i = 2; i < n; i++) {if (notPrime[i] == false) {count++;for (int j = 2; i*j < n; j++) {notPrime[i*j] = true;}}}return count; }//這里用了不斷累加的方法 感覺也不錯 public static int countPrimes3(int n) {boolean[] m = new boolean[n];int count = 0;for (int i=2; i<n; i++) {if (m[i]) {continue;}count++;for (int j=i; j<n; j=j+i) {m[j] = true;}}return count;}

git:https://github.com/woshiyexinjie/leetcode-xin/tree/master/src/main/java/com/helloxin/leetcode/algorithms?

轉載于:https://my.oschina.net/u/2277632/blog/2962468

總結

以上是生活随笔為你收集整理的Count Primes(leetcode204)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。