0

I have the following C++17 program, which I am running on GNU G++17 7.3.0, which merely adds two square sums as shown below: `

#include <iostream>
using namespace std;
int main ()
{
  int lines;
  cin>>lines;
  for(int i = 0; i<lines; i++){ 
  int m;
  int n;
  cin>>n>>m;
  long sum = m*n*(n+1)/2;
  sum=sum+(m-1)*m/2;
  
  cout<<sum<<endl;
}
  return 0;
}

`

The code works fine for small values, but when I input the values 10000 10000 for n and m, I get a weird answer. I am supposed to get sum = 500099995000. However, I get sum = -263694984. I suspect the value is just too big, so I changed the n and m to long datatypes, but I still get the same error. What is happening here? Furthermore, what are the conventions around these datatype sizes? I hate when I have an algorithm working but not for large input values, which wrap around or overflow.

Thanks in advance!

DjuroPucar
  • 11
  • 2
  • 6
    There exist libraries for large integers, e.g. GMP or MPIR – john Dec 27 '22 at 18:39
  • 2
    `int` and `long` may be the same size, they are on Windows. You can use `sizeof(type)` to figure that out. You could use `long long` or `int64_t` instead. – Retired Ninja Dec 27 '22 at 18:40
  • 4
    Note: Even if `long` is 64 bit for your compiler, the expression `m*n*(n+1)/2` does all calculations using the `int` data type. Any widening conversion that may happen, only happens after the expression on the rhs has been evaluated completely, except for the widening conversion to the target type... – fabian Dec 27 '22 at 18:50

0 Answers0