gpt4 book ai didi

c - C 中的素数和 is_prime

转载 作者:行者123 更新时间:2023-11-30 21:02:41 24 4
gpt4 key购买 nike

我正在编写一个程序来查找用户输入n中包含的所有素数。我在使用 is_prime 函数时遇到问题。

#include <stdio.h>
#include <math.h>

main() {
int n;
int k;

// gets user input for length of string
// and stores it as n
printf("Enter the value of n:");
scanf("%d", &n);

for (k = 2; k <= n; k++) {
if (is_Prime(k) == 1) {
printf("Printing primes less than or equal to %d: /n %d, &n, &k");
}
}

我希望输出看起来像这样,但我不确定如何在不为每个素数使用不同变量的情况下打印列表。

Printing primes less than or equal to 30:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29.


//here is the is_Prime function
is_Prime (int n)
{
for(j = 2; j <= n/2; j++)
{
if(n%j != 0)
{
return 1;
break;
}
}
if(n%j == 0 )
return 0;
}

我不知道如何调用 is_prime 子例程?有什么帮助吗?

最佳答案

printf("Printing primes less than or equal to %d:\n", n);
for(k = 2; k <= n; k++)
{
if(is_Prime(k) == 1)
{
printf("%d, ", k);
}
}

关于c - C 中的素数和 is_prime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786479/

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