筛法求解1到n的素数个数c语言
时间: 2023-03-30 09:00:40 浏览: 109
可以使用埃氏筛法或欧拉筛法来求解1到n的素数个数。以下是使用埃氏筛法的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int countPrimes(int n) {
if (n <= 2) {
return ;
}
bool *isPrime = (bool*)malloc(sizeof(bool) * n);
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
int count = n - 2;
for (int i = 2; i * i < n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
if (isPrime[j]) {
isPrime[j] = false;
count--;
}
}
}
}
free(isPrime);
return count;
}
int main() {
int n = 100;
int count = countPrimes(n);
printf("There are %d primes less than %d.\n", count, n);
return ;
}
输出结果为:There are 25 primes less than 100.
阅读全文