Sensitive operations with big numbers in C++

30 views Asked by At

I want to make a program that takes a number input from the user and tells whether the number is a square of an integer or not. My code runs correctly when inputs are small numbers. But when I enter really big numbers like 2^60+100, it says number is a square of an integer, but in fact it is not. (it works fine when it takes 2^60, it says number is a square of an integer. it also works fine when it takes 2^61, it says number is not a square of an integer) By the way, I am using long long datatype to store big numbers. A portion of my code is like this:

long long num = pow(2, 60);
if (pow(floor(sqrt(num)), 2) == num) {
    cout << "a"; // true
}
else {
    cout << "b";
}
long long num = pow(2, 60)+100;
if (pow(floor(sqrt(num)), 2) == num) {
    cout << "a"; // wrong
}
else {
    cout << "b";
}
long long num = pow(2, 61);
if (pow(floor(sqrt(num)), 2) == num) {
    cout << "a";
}
else {
    cout << "b"; // correct
}

My code should be so sensitive that can distinguish the difference between 2^60 and 2^60+1

The solution for this does not work in my situation. Solutions second parameter is a constant meanwhile in my code, it is not constant and the code still runs incorrectly.

0

There are 0 answers