原題鏈接 https://leetcode.com/problems/count-primes/
Description:
Count the number of prime numbers less than a non-negative number, n.
數素數有多少個。
方法可以用一般的方法,就是判斷從1-sqrt(n) 有沒有能夠整除的數。
當然可以排除一些數,比如除2以外偶數都不是素數。
當然還有一種方法叫素數測試,就是利用費馬小定理和二次探測,可以在很大的概率下該數就是素數。
class Solution {
public:
int countPrimes(int n) {
int ans = 0;
if (n > 2)ans++;
for (int i = 3; i < n; i += 2)
if (isPrime(i))ans++;
return ans;
}
bool isPrime(int& x)
{
int up = sqrt(x);
for (int i = 3; i <= up; i += 2)
{
if (x % i == 0)return false;
}
return true;
}
};