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