Count Primes(leetcode204)
阿新 • • 發佈:2018-11-29
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