modulus operations on long long in c++

lilott8 picture lilott8 · Jun 12, 2011 · Viewed 8.7k times · Source

I am working on prime factorization on large numbers (mainly, project 3 @ project Euler. I need to use the modulus on numbers declared as long long. Everytime I try to modulus that gigantic number I get a floating point exception. Any help would be profusely appreciated. Thanks.

I have run this through gdb and see what's happening. Below is my code. It's very rough logic at this point. Please do not give me the answer to the problem. I will gladly accept help on making this better, just please do not give me the straight up answer. Thanks :)

long factor(long number) {
  string br = "\n\r";
  long x = 0;
  /*this modulus variable is an attempt
  to move the answer into a long long container
  to see if that solves my floating point exception,
  it didn't*/
  long long modulus;

  while(x <= number) {
    modulus = number % x;
    if(modulus == 0) {
      cout << number/x << br;
      return factor(number/x);
    }//if number % x
    else {
      return x;
    }//else
    x++;
  }//while

}//factor

Answer

Andrew White picture Andrew White · Jun 12, 2011

Don't try to mod by 0, it's undefined! Doing so will result in a divide-by-zero error.

long x = 0;
modulus = number % x; // x is 0 here and thus not valid

To expand a bit on my answer, per Wikipedia's article on Modulo Operations

a modulo 0 is undefined in the majority of systems, although some do define it to be a.