编码一个计算两个整数间的素数个数的代码
时间: 2024-11-17 20:29:31 浏览: 13
为了编写一个计算两个整数之间(包括这两个数本身)素数个数的程序,你可以使用Sieve of Eratosthenes(埃拉托斯特尼筛法)来预生成一定范围内的所有素数,然后遍历指定区间找出其中的素数。以下是使用C语言的一个例子:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_PRIME 10000
// Function to generate primes using Sieve of Eratosthenes
bool* sieve_of_eratosthenes(int limit) {
bool prime[MAX_PRIME + 1];
for (int i = 2; i <= MAX_PRIME; i++)
prime[i] = true;
for (int p = 2; p * p <= MAX_PRIME; p++) {
if (prime[p]) {
for (int i = p * p; i <= MAX_PRIME; i += p)
prime[i] = false;
}
}
return prime;
}
// Function to count primes between two numbers
int count_primes_between(int start, int end, bool* prime) {
int count = 0;
for (int i = start; i <= end; i++) {
if (prime[i])
count++;
}
return count;
}
int main() {
int start_num, end_num;
printf("请输入两个整数,之间将会统计素数个数:\n");
scanf("%d%d", &start_num, &end_num);
if (start_num > end_num) {
int temp = start_num;
start_num = end_num;
end_num = temp;
printf("交换输入顺序:现在从 %d 到 %d 寻找素数。\n", start_num, end_num);
}
bool* primes = sieve_of_eratosthenes(end_num);
int result = count_primes_between(start_num, end_num, primes);
free(primes); // 释放内存
printf("在%d到%d之间的素数个数为:%d\n", start_num, end_num, result);
return 0;
}
阅读全文