4

我有一个我似乎无法解决的问题。我随机生成数字以确定我的数字是否是相对素数。

这是给我一个浮点异常的函数:

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));

非常感谢您的帮助!

4

2 回答 2

6

You'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

于 2010-02-22T01:32:22.280 回答
4

值是exponent零吗?如果是这样,那就是被零除的异常。

于 2010-02-22T01:23:27.403 回答