gpt4 book ai didi

c - 打印不超过 n 的质数

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:16 25 4
gpt4 key购买 nike

我写了一些代码来询问用户 n,然后打印直到 n 的质数。然而,当我使用它时,即 10,它只打印非素数

 /* Asks for the amount of prime numbers you would like to print, then prints them */

#include <stdio.h>

int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);

for (i = 2; i <= n; i++) {
check = 0;

for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}

return 0;
}

How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10

我已经尝试了所有方法,但我认为我遗漏了一些非常微不足道的东西!

最佳答案

它应该是这样的:

for (i = 2; i <= n; i++)
{
check = 0;

for (j = 2; j < i ; j++)
{

if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}

此外,在内部循环中,您不必将数字除以 j < i。 .你不必超越 i/2 .

关于c - 打印不超过 n 的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com