Floating point exception thrown by rand () in C ++

I have a problem that I cannot solve. I randomly generate numbers to determine if my numbers are relative simply.

Here is a 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 a random seed change in another function by doing the following:

 srand(time(NULL));

Many thanks for your help!

+3
source share
2 answers

You move exponentright in the while loop until you reach 0.
Thus, the second time you reach base = rand() % exponent; exponent, it is 0 and you have a division by 0

+5
source

exponent ? , " " .

+4

Source: https://habr.com/ru/post/1733820/


All Articles