【发布时间】:2013-05-14 07:49:56
【问题描述】:
对我说的问题是这样的:
“600851475143 的最大质因数是多少?”
该程序用于查找答案正是使用 C:
#include<math.h> // for remainder because % does not work with double or floats
#include<stdio.h>
main()
{
double x=600851475143,y=3.0;
while(x!=y) // divide until only the number can divide itself
{
if(remainder((x/y),1)==0.0) // if x is divisible by y which means it is a factor then do the magic
{
x=x/y; // divide the number x by y thereby reducing one constituent factor
}
y=y+2; // add 2 simply because only odd numbers can be prime and hence only prime numbers can be prime factors
}
printf("%lf",y); // do the printing magic
}
问题正是要问你,我试图检查 x 除以所有奇数,但请注意,并非所有奇数都不是素数,算法中的这个缺陷应该会导致答案错误,因为实际上我应该检查主要因素(不是奇数因素)。
令人惊讶的是这个程序吐出的答案是正确的,我检查了答案。
我该如何解决这个问题?这没有意义。
【问题讨论】:
-
算法不正确并不意味着它必须总是给出错误的结果。就像程序崩溃不需要未定义的行为一样。顺便说一句,您最好避免使用浮点数来解决与整数相关的问题。使用
if (x % y == 0)检查 x 是否可以被 y 整除。 最重要的是:格式化您的代码。 -
没什么——只是在这种情况下,在大多数平台上使用
ints 将不起作用,并且 OP 可能没有意识到这一点。 -
@xabhisan:做得好,但使用
int64_t比切换到浮点更合适,这会带来一系列完全不同的问题。 -
代码存在更多问题:(1) 2 是质数。 (2)应该计算两次的因素呢(例如数字27,质数3应该计算3次)
-
@xabhisan 好吧,即使是坏掉的时钟也会一天两次显示正确的时间。这个算法也是。
标签: c algorithm primes prime-factoring