Unexpected results when working with very big integers on interpreted languages

I am trying to get the sum of 1 + 2 + … + 1000000000, but I’m getting funny results in PHP and Node.js. PHP $sum = 0; for($i = 0; $i <= 1000000000 ; $i++) { $sum += $i; } printf(“%s”, number_format($sum, 0, “”, “”)); // 500000000067108992 Node.js var sum = 0; for (i … Read more

Why is unsigned integer overflow defined behavior but signed integer overflow isn’t?

Unsigned integer overflow is well defined by both the C and C++ standards. For example, the C99 standard (§6.2.5/9) states A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that … Read more

(-2147483648> 0) returns true in C++?

-2147483648 is the smallest integer for integer type with 32 bits, but it seems that it will overflow in the if(…) sentence: if (-2147483648 > 0) std::cout << “true”; else std::cout << “false”; This will print true in my testing. However, if we cast -2147483648 to integer, the result will be different: if (int(-2147483648) > … Read more