1

I am trying to execute a simple long multiplication but it is not showing the correct the output. here is the sample code

'''
#include<iostream>
using namespace std;
int main ()
{
    long long int c=100000*90000;
    cout<<c;
    return 0;
}
'''

cout of variable c is: 410065408

I dont know why it is displaying the garbage value instead of 9000000000.

Anas Raza
  • 11
  • 2

2 Answers2

5

On a platform with a 32 bit int, 100000 and 90000 are int types (Note that on platforms with a 16 bit int they would be long types and a similar analysis to what I present here would apply to a 32 bit long.)

Hence you are multiplying two int types. You are overflowing the int, with undefined results, although it's no coincidence that 9000000000 - 410065408 is a multiple of 232 (but don't rely on that since it's little more than a manifestation of undefined behaviour).

100000LL * 90000

is a fix.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Basically I have generate random numbers (which can be long as 100000) to fill the array and calculate the maximum pair wise product. – Anas Raza Oct 15 '20 at 08:10
3

The type of 100000 is (probably 1) int (on your system). The type of 90000 (probably) is int (on your system). You are multiplying two int objects. int is guaranteed to represent numbers up to 32'767. On modern x86 systems it can represent up to 2'147'483'647. Those maximums are less than 9'000'000'000. As such, the behaviour of the program is undefined.

The fact that you initialise a long long using this overflowed int is irrelevant to the result. You must perform the multiplication on long long objects to get a 64 bit (at least) multiplication.


1 Assuming those numbers are representable as int on your system, which it is on modern x86 systems. It could be long on some systems.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • @FrançoisAndrieux: I still maintain my conjecture that the majority of systems running C and C++ programs at the time of my writing this have a 16 bit `int` type. – Bathsheba Oct 14 '20 at 14:22