Assuming you are using a common architecture, the problem is that the calculation of calculating i*i full. The result cannot be stored in a 32-bit integer value. You can try adding cout << temp << endl; after this calculation. At the end he will print:
2144523481 2146190929 2147117569 -2146737495 Segmentation fault
In the future, you will want to run your code in the debugger. This makes it easier for you to find these things. I suspect CodeBlocks offers a graphical debugger. (Otherwise, be sure to compile with -ggdb and run your program with gdb )
Since you are on a 64-bit platform, you can use 64-bit unsigned integers to get a larger range. unsigned long long (C99, C ++ 0x) is a good way to ask for "the biggest you have, which is cheap enough." (Even if one long long can span two registers, as is the case with the 64-bit data type on IA32)
Alternatively, you can add a check to automatically check that number < sqrt(numeric_limits<int>::max()) before entering the loop.
source share