gpt4 book ai didi

c - 我的 Checkprime.c 程序有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:12 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来检查给定数字是否为素数。但是,我的程序只给了我 2 时间表,我不知道为什么。

这是我的主要类(class):

#include <stdio.h>
#include "defs.h"
#include "checkprime.c"


int Prime[MaxPrimes];

int main()
{
int UpperBound;
int N;
int *ba = &UpperBound;

printf("enter upper bound\n");
scanf("%d",ba);

Prime[2] = 1;

for (N = 3; N <= *ba; N+= 2)
{
CheckPrime(N);
if (Prime[N]== 1) printf("%d is a prime\n",N);
}
}

这是我的 checkprime.c

#include "defs.h"
#include "externs.h"


int CheckPrime(int K)
{

int J;


J = 2;

while (1)
{
if (Prime[J] == 1)
{
if (K % J == 0)
{
Prime[K] = 0;
return 0;
}
J++;
}
break;
}

Prime[K] = 1;
}

最佳答案

CheckPrime 在循环退出条件方面存在一些问题。请改用以下内容:

int CheckPrime(int K)
{
int J;

for (J=2; J*J <= K; J++) {
if (Prime[J] == 1) {
if (K % J == 0) {
Prime[K] = 0;
return 0;
}
}
}

Prime[K] = 1;
return 1;
}

它的其余部分应该适用于此更改。

关于c - 我的 Checkprime.c 程序有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486705/

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