Why is pow() producing a wrong answer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    unsigned ll k, l;
    cin >> k >> l;

    int i = 1;
    unsigned ll n;
    while(true){
        n = pow(k, i);
        cout << n << endl;

        if(n > l){
            cout << "NO";
            return 0;
        }
        if(n == l){
            cout << "YES" << endl;
            cout << (i-1);
            return 0;
        }
        ++i;
    }
    return 0;
}


Using this input:
5
25


When it reaches i = 2, it somehow outputs pow(5,2) to 24 not 25 lol wtf?
PS: ll is a define for long long
Last edited on
assign the value into a double and print it with about 10 digits after the decimal place.

its probably getting 24.999999999999999999999999999999999999999999

and integer truncating that to 24.

for simple integer powers, just use X*X. Pow is slower because it supports fractional powers like x to the pi power, and for the same reasons it is internally more complex than just X*X and the algorithm it uses can have roundoff.


Last edited on
It's a floating point precision error I guess.
Those kind of errors occur sometime using pow(), that's why it's important to stay focused using it and don't make mistakes.
If you find those kind of errors to troubling for you, you can try using some programs to help you with it. I tend to use checkmarx but there are many you can use.
Good luck with it!
Ben.
Topic archived. No new replies allowed.