gpt4 book ai didi

计算范围内素数的代码返回一半的数字

转载 作者:行者123 更新时间:2023-11-30 16:09:37 25 4
gpt4 key购买 nike

这段代码的某些部分是错误的,我无法弄清楚。我逻辑地编写代码来计算两个给定数字之间的素数,但代码返回给定数字范围的一半。函数工作正常,但 while 循环的逻辑错误

代码:

#include<stdio.h>

int checkPrime(int isItPrime);

int main()
{

printf("Counting Prime Numbers between twos\nEnter two numbers , the First number must be smaller\n");
int num1, num2;
scanf("%d%d", &num1, &num2);
int count = 0;
while(num1<num2)
{
num1++;
if(checkPrime(num1)==1)
count++;
}
printf("%d\n", count);

return 0;
}

int checkPrime(int isItPrime)
{

int result = 0, j = 2;
while(result < isItPrime)
{
result = (isItPrime%j);
j++;
if (result==0)
return 0;
else if (result!=0)
return 1;
}

}

最佳答案

看看这是否有效,我希望它有效:

 #include<stdio.h>

int checkPrime(int n);

int main()
{

printf("Counting Prime Numbers between twos\nEnter two numbers , the First number must be smaller\n");
int num1, num2;
scanf("%d%d", &num1, &num2);
int count = 0;
while(num1<num2)
{
num1++;
if(checkPrime(num1)==1)
count++;
}
printf("%d\n", count);

return 0;
}
int checkPrime(int n)
{

if (n <= 1)
return 0;
for (int i = 2; i < n; i++)
if (n % i == 0)
return 0;

return 1;
}

关于计算范围内素数的代码返回一半的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098331/

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