Search code examples
c++integer-overflow

C++, Integer Overflow?


I made a program to find the factors of a number:

#include <iostream>
#include <cmath>
using namespace::std;
int main() {
    long int n = 6008514751432;
    int i = 1;
    while (i <= n/2) {
        if (n % i == 0)
            cout << i << " ";
        i++;
    }
}

I am using xCode BTW It works fine with smaller numbers, like 2000 lets say, or even 200000. But, when I get up to 6008514751432, which is the number I need to know, it doesn't work, it just says the program is running and displays nothing! What is going on?

Update: When I run the program and wait about 2 minutes, it says:

Warning: the current language does not match this frame.
Current language:  auto; currently c++
(gdb) 

Solution

  • Depending on your platform, you find that 6008514751432 is too large for the type long int. You need to make sure you are using a type that holds a 64-bit integer type.

    Also, if you are just trying to find the factors of a number, there is no need to look higher than sqrt(n) as factors greater than that have a corresponding co-factor less than that. Make sure to out the sqrt outside the loop itself.

    On a system where long int is larger than int, note that you'll find that at some point i wraps to 0