[LeetCode] 204. Count Primes 計數質數
阿新 • • 發佈:2018-03-12
inf function wikipedia rip end cto ins java 自然
Description:
Count the number of prime numbers less than a non-negative number, n
click to show more hints.
References:How Many Primes Are There?
Sieve of Eratosthenes
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
計數出小於非負整數n的質數數量。質數(prime number)又稱素數,有無限個。質數定義為在大於1的自然數中,除了1和它本身以外不再有其他因數。
解法:埃拉托斯特尼篩法 Sieve of Eratosthenes
如果一個數是另一個數的倍數,那這個數肯定不是質數。利用這個性質,可以建立一個質數數組,從2開始將素數的倍數都標註為不是質數。第一輪將4、6、8等表為非質數,然後遍歷到3,發現3沒有被標記為非質數,則將6、9、12等標記為非質數,一直到N為止,再數一遍質數數組中有多少質數。
Java:
public class Solution { public int countPrimes(int n) { boolean[] prime = new boolean[n]; Arrays.fill(prime, true); for(int i = 2; i < n; i++){ if(prime[i]){ // 將i的2倍、3倍、4倍...都標記為非素數 for(int j = i * 2; j < n; j = j + i){ prime[j] = false; } } } int count = 0; for(int i = 2; i < n; i++){ if(prime[i]) count++; } return count; } }
Python:
class Solution: # @param {integer} n # @return {integer} def countPrimes(self, n): isPrime = [True] * max(n, 2) isPrime[0], isPrime[1] = False, False x = 2 while x * x < n: if isPrime[x]: p = x * x while p < n: isPrime[p] = False p += x x += 1 return sum(isPrime)
Python:
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <= 2: return 0 vis = [False] * n for i in range(2, int(n ** 0.5) + 1): if vis[i]: continue j = i while j * i < n: vis[j * i] = True j += 1 ans = 0 for i in range(2, n): if not vis[i]: ans += 1 return ans
C++:
class Solution { public: int countPrimes(int n) { if(!n||n==1) return 0; vector<bool> isPrime(n,true); // Loop‘s ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for(int i=2;i*i<n;++i) { if(!isPrime[i]) continue; //填表起點i*i,如3*3,因為3*2已填,步長+i for(int j=i*i;j<n;j+=i) { isPrime[j]=false; } } int count=0; for(int i=2;i<n;++i) { if(isPrime[i]) ++count; } return count; } };
[LeetCode] 204. Count Primes 計數質數