题目描述:
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。
力扣链接:https://leetcode.cn/problems/count-primes/submissions/
案例:
解决方案:
解决方案一:
代码:
public int CountPrimes(int n) {
int count = 0;
for(int i = 2;i<n;i++){
if(IsPrime(i)){
count++;
}
}
return count;
}
public bool IsPrime(int num)
{
bool b = true;
for (int i = 2; i < num / 2 + 1; i++)
{
if (num % i == 0)
{
b = false;
}
}
return b;
}
提交结果:
方案二:
代码:
public int CountPrimes(int n) {
bool[] isPrim = new bool[n];
Array.Fill(isPrim, true);
for (int i = 2; i * i < n; i++) {
if (isPrim[i]) {
for (int j = i * i; j < n; j+=i) {
isPrim[j] = false;
}
}
}
int cnt = 0;
for (int i = 2; i < n; i++) {
if (isPrim[i]) {
cnt++;
}
}
return cnt;
}
public bool IsPrime(int num)
{
bool b = true;
for (int i = 2; i < num / 2 + 1; i++)
{
if (num % i == 0)
{
b = false;
}
}
return b;
}
提交结果: