Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Exception Caused By rand() In c++

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!

like image 505
Alex Avatar asked Dec 29 '22 01:12

Alex


2 Answers

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

like image 168
f4. Avatar answered Jan 09 '23 05:01

f4.


Is the value of exponent zero? If so, that a divide-by-zero exception right there.

like image 22
Justicle Avatar answered Jan 09 '23 06:01

Justicle