newprint
newprint

Reputation: 7136

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 !

Upvotes: 5

Views: 620

Answers (2)

Ed Heal
Ed Heal

Reputation: 60007

Try

product = 2137483647LL * 2137483647LL; 

to ensure that the compile treats the numbers as long long

Upvotes: 6

Mysticial
Mysticial

Reputation: 471259

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;

Upvotes: 14

Related Questions