LeetCode OJ Count Primes
发布时间:2020-12-13 20:10:37 所属栏目:PHP教程 来源:网络整理
导读:Description: Count the number of prime numbers less than a non-negative number, n click to show more hints. Credits: Special thanks to@mithmattfor adding this problem and creating all test cases. 素数挑选法。 int countPrimes(int n) {bool *
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. 素数挑选法。 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;
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |