Kakarot_7
Kakarot_7

Reputation: 342

sqrt function in C++ issue

#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!

Upvotes: 0

Views: 364

Answers (1)

Martin Perry
Martin Perry

Reputation: 9527

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)

Upvotes: 6

Related Questions