Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect product of two INT_MAX numbes in C/C++

In my case, product of two INT_MAX numbers is 296447233, which is incorrect.

long long int product = 0;
product = 2137483647 * 2137483647;
printf("product: %lli\n", product);

What I am doing wrong, and how to correct it ?? Thanks !

like image 583
newprint Avatar asked Feb 29 '12 18:02

newprint


1 Answers

Both of your 2137483647 are of type int. So they stay that type and overflow.

Make them long longs:

product = 2137483647LL * 2137483647LL;

or cast:

product = (long long)2137483647 * 2137483647;
like image 57
Mysticial Avatar answered Oct 17 '22 15:10

Mysticial