gpt4 book ai didi

c - 涉及威尔逊定理的素数测试未按计划进行

转载 作者:行者123 更新时间:2023-12-04 07:06:06 24 4
gpt4 key购买 nike

我刚刚开始编程,遇到了一个我似乎无法弄清楚的问题。我编写了这个函数 isPrime,它似乎总是通过相等性测试。我可以确认 factorial 函数有效,因为我已经单独对其进行了测试。

Wilson 定理指出,如果 (p - 1),则 p 是素数! + 1 是 p 的倍数。

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

void isPrime(double p);
double factorial(double n);

int main(void) {
double userInput;
while(1) {
scanf("%lf", &userInput);
isPrime(userInput);
}
return 0;
}

//

double factorial(double n) {
if(n <= 1)
return n;
else
return n * factorial(n - 1);
}

void isPrime(double p) {
if(modf(factorial(p - 1) + 1, &p) == 0)
printf("Prime!\n");
else
printf("Not prime!\n");
}

最佳答案

不要使用 double 来保存整数。舍入误差将使相等性测试完全虚假。参见“What Every Computer Scientist Should Know about Floating Point”。

关于c - 涉及威尔逊定理的素数测试未按计划进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7936781/

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