c++ 中由 rand() 引起的浮点异常
我有一个似乎无法解决的问题。我随机生成数字,以确定我的数字是否是相对论素数。
这是给我一个浮点异常的函数:
bool modularExponentiationTest(unsigned long long exponent, unsigned long long modulus)
{
short index = 0;
unsigned long long base;
unsigned long long result;
do
{
result = 1;
base = rand() % exponent; // <--CAUSED BY THIS
while (exponent > 0)
{
if (exponent & 1)
result = (result * base) % modulus;
exponent >>= 1;
base = (base * base) % modulus;
}
if (result != 1)
return false;
}while(++index < 10);
return true;
}
我通过执行以下操作在不同的函数中随机播种:
srand(time(NULL));
非常感谢您的帮助!
I have an issue that I can't seem to solve. I am randomly generating numbers in order to determine if my numbers are relativity prime.
Here is the function that gives me a Floating Point Exception:
bool modularExponentiationTest(unsigned long long exponent, unsigned long long modulus)
{
short index = 0;
unsigned long long base;
unsigned long long result;
do
{
result = 1;
base = rand() % exponent; // <--CAUSED BY THIS
while (exponent > 0)
{
if (exponent & 1)
result = (result * base) % modulus;
exponent >>= 1;
base = (base * base) % modulus;
}
if (result != 1)
return false;
}while(++index < 10);
return true;
}
I did seed random in a different function by doing the following:
srand(time(NULL));
Thank you very much for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在 while 循环中将
指数
向右移动,直到达到 0。所以第二次到达时
base = rand() % exponent;
exponent
是 0 并且除以 0You're shifting
exponent
to the right in the while loop until it reach 0.So the second time you reach
base = rand() % exponent;
exponent
is 0 and you have a division by 0指数
的值为零吗?如果是这样,那就是被零除异常。Is the value of
exponent
zero? If so, that a divide-by-zero exception right there.