Why the overflow?

When I run the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

long f(int n){ 
  long result;
  result = n*(3*n-1)/2; 
  return result;  
}

int main(){
  cout << f(26755) << endl;   
  cout << f(26756) << endl; 
  return 0;
}


I get

1073731660
-1073671722

I do not understand why! Please help because I am getting crazy!
in the expression n*(3*n-1)/2, the type of every operand (n, 3, 1, 2) is int, therefore the type of the result is also int
I believe that in the case of operators having the same priority ranking, it is simply read from left to right. Since * and / have the same priority, it will calculate the n*(3*n-1) before it gets to the /2, and because it overflows (max value of signed long being 2^31 -1), the division happens to the negative figure.

Someone feel free to correct me though.

edit: I just tested it with the same result, and then I did the same with the /2 earlier in the formula and got 2 positive numbers.
Last edited on
Thanks Cubbi!

I was assuming that there would be an automatic upcast!
Hi manudude03!

No even if I use parenthesis (n*(3*n-1))/2, the problem remains

Edit: Sorry I am talking rubbish!
Last edited on
brackets have a higher priority than / so it would try and evaluate (n*(3*n-1)) first, which overflows. Try doing the same thing, but use n/2 * (3*n-1) instead.
Last edited on
A signed long variable can store values up to 2147483647.

When you call f(26756), according to the order of operations, the compiler performs three multiplications before it divides in n * (3 * n - 1) / 2. The problem is that n * (3 * n - 1) > 2147483647; this causes the overflow.

If you rewrite the operation like this, it will work: n * (n - 1) / 2 * 3.

Edit: someone got ahead of me. :-)
Last edited on
I was assuming that there would be an automatic upcast!

Types are decided at compile time: int times int returns int. It can't recompile the code to return and process a long if at runtime the value didn't fit in the int
Thank you all for your help!
Topic archived. No new replies allowed.