问题描述
||
我正在大数上进行素因数分解(主要是project 3 @ project Euler。我需要在声明为long long的数字上使用模数。每次我尝试对那个巨大的数模数时,都会得到一个浮点异常。任何帮助都是非常感谢。
我已经通过gdb运行了此程序,然后看看发生了什么。下面是我的代码。在这一点上,这是非常粗糙的逻辑。请不要给我答案。我会很乐意接受帮助改善此问题的,请不要直接给我答案。谢谢 :)
long factor(long number) {
string br = \"\\n\\r\";
long x = 0;
/*this modulus variable is an attempt
to move the answer into a long long container
to see if that solves my floating point exception,it didn\'t*/
long long modulus;
while(x <= number) {
modulus = number % x;
if(modulus == 0) {
cout << number/x << br;
return factor(number/x);
}//if number % x
else {
return x;
}//else
x++;
}//while
}//factor
解决方法
不要尝试以0为模,这是未定义的!这样做将导致被零除的错误。
long x = 0;
modulus = number % x; // x is 0 here and thus not valid
根据Wikipedia关于Modulo Operations的文章,扩大我的答案
在大多数系统中,模0是未定义的,尽管有些人确实将其定义为a。
, 从...开始
long x = 1 ;
避免被零除。