0

So my code looks like this:

unsigned long i=(27984 * 619246) + (1402 * 615589);
cout<<" i= "<<i;

I don't use the variable i anywhere else etc

Output looks like this

 i= 1012166658

The correct answer is 18192035842 . WHY is this happening?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Ankitha Kini
  • 133
  • 1
  • 6
  • 4
    The terms on the RHS are getting truncated due to overflow. There is probably a duplicate of this question/problem in SO. – R Sahu May 24 '21 at 16:31
  • 1
    I think your constants default to signed ints, so it’s overflowing? – Steffen Schumacher May 24 '21 at 16:33
  • 4
    Related: [Why does long long n = 2000*2000*2000*2000; overflow?](https://stackoverflow.com/q/66354756/673852) – Ruslan May 24 '21 at 16:36
  • 2
    Computer don't have infinite memory. Use the right kind of memory with the right kind of precision for your purposes. – Guillaume Racicot May 24 '21 at 16:36
  • 1
    `unsigned long i=(27984 * 619246) + (1402 * 615589);` is `unsigned long i = int((int * int) + (int * int));` which may be a problem if the expression overflows an `int`. – Eljay May 24 '21 at 16:50

1 Answers1

2

Try this:

#include<iostream>
#include <string>
using namespace std;

int main() {
    unsigned long long i = (27984ULL * 619246ULL) + (1402ULL * 615589ULL);
    cout << " i= " << i;
}

using the long long literal suffix LL, and upgrading the type to a bigger type solves the problem.

I use the U (unsigned) literal suffix so that we can have it the same as the resulting type.

With your original code, there was an overflow (the result did not fit in the original type, or the operator) so it returned a truncated version. An example compiler warning that I got:

warning C4307: '*': signed integral constant overflow