生成质数的代码怎么写用C语言
时间: 2023-05-13 18:07:01 浏览: 101
生成质数的代码可以使用C语言的嵌套循环来实现,具体代码如下:
```c
#include <stdio.h>
int main() {
int n, i, j, flag;
printf("请输入一个正整数:");
scanf("%d", &n);
printf("1-%d之间的质数有:\n", n);
for (i = 2; i <= n; i++) {
flag = 1;
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
```
这段代码会输出1到n之间的所有质数。
相关问题
生成素数表的c语言代码
生成素数表的C语言代码通常涉及埃拉托斯特尼筛法(Sieve of Eratosthenes),这是一种古老而高效的算法。这里是一个简单的示例,它会创建并打印出一定范围内的所有素数:
```c
#include <stdio.h>
#include <stdbool.h>
void sieve_of_eratosthenes(int n) {
bool prime[n+1];
memset(prime, true, sizeof(prime)); // 初始化所有数字为素数
for (int p=2; p*p<=n; p++) {
if (prime[p] == true) {
// 将p的所有倍数标记为合数
for (int i=p*2; i <= n; i += p)
prime[i] = false;
}
}
printf("素数表(小于 %d):\n", n);
for (int p=2; p<=n; p++)
if (prime[p])
printf("%d ", p); // 打印素数
}
int main() {
int range;
printf("请输入一个范围(大于1): ");
scanf("%d", &range);
sieve_of_eratosthenes(range);
return 0;
}
```
用c语言生成100以内素数的代码
当然可以,以下是一种可能的实现:
```c
#include <stdio.h>
#include <stdbool.h>
bool is_prime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
for (int i = 2; i <= 100; i++) {
if (is_prime(i)) {
printf("%d ", i);
}
}
return 0;
}
```
这个程序会从 2 到 100 按顺序输出素数。
阅读全文
相关推荐













