0
#include <iostream>
#include <cmath>

using namespace std;

int main(){
    
    int n;
    cin >> n;
    
    int i = sqrt(1 + 2 * n * (n + 1)) - 1;
    
    cout << i;
}

I have written a simple program which utilizes the sqrt() function in C++. The above program prints out a negative value on the console for n = 32768 even though the input to sqrt() is positive. I tried changing the statement from int i = sqrt(1 + 2 * n * (n + 1)) - 1; to
double i = sqrt(1 + 2 * n * (n + 1)) - 1; but the error is not resolving.

Output:

32768
-2147483648

The above output is for int i = sqrt(1 + 2 * n * (n + 1)) - 1;

Please help!

Kakarot_7
  • 302
  • 1
  • 5
  • 14

1 Answers1

6

Change int n to double n. Your calculation 1 + 2 * n * (n + 1) overflows the range of int which for 32bits is -2,147,483,648 to 2,147,483,647.

Side note: int may not be 32bit, it depends on the platform (however, usually most of the time it is 32bit)

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
  • That's right, except overflow isn't guaranteed. Attempting to cast a double outside of representable range to int is UB. See SO post [Handling overflow when casting doubles to integers in C](https://stackoverflow.com/a/30424410/13223986). – Pascal Getreuer Sep 09 '20 at 00:50