LeetCode OJ Count Primes
來源:程序員人生 發(fā)布時間:2015-05-21 08:15:25 閱讀次數(shù):2422次
Description:
Count the number of prime numbers less than a non-negative number, n
click to show more hints.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
素數(shù)挑選法。
int countPrimes(int n) {
bool * IsPrime = (bool*)malloc(sizeof(bool) * n);
for (int i = 0; i < n; i++) IsPrime[i] = true;
for (int i = 2; i < n; i++) {
if (IsPrime[i]) {
for (int j = i + i; j < n; j += i) {
IsPrime[j] = false;
}
}
}
int ans = 0;
for (int i = 2; i < n; i++) if (IsPrime[i]) ans++;
free(IsPrime);
return ans;
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈