4

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!

Alex
  • 426
  • 1
  • 6
  • 15

2 Answers2

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

f4.
  • 3,814
  • 1
  • 23
  • 30
  • 1
    Well spotted, `exponent` is being downshifted to zero, and there's no guard against it being zero. – Justicle Feb 22 '10 at 01:36
  • Good catch. Make your arguments const. Altering pass by value arguments inside of a function hides this sort of bug. Check for zero just before performing the modulus in each case. – thebretness Feb 22 '10 at 01:38
  • Thanks very much! I just didn't see that. – Alex Feb 22 '10 at 01:38
4

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

Justicle
  • 14,761
  • 17
  • 70
  • 94
  • You should probably check both the modulus and exponent variables for zero since you modulus with both of them. – thebretness Feb 22 '10 at 01:28
  • @Alex you could be more helpful - what is the exception generated and what is the value of both `rand()` and `exponent`? – Justicle Feb 22 '10 at 01:30