0

For the below code:

int digsum(ll num) {  //function to calculate sum of digits
    if (num < 0)
        num = abs(num);
    int ans = 0;
    while (num != 0) {
        ans = ans + num % 10;
        num = num / 10;
    }
    return ans;
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);

    int a, b, c, cnt = 0;
    long long x;
    cin >> a >> b >> c;

    for (int i = 0; i <= 72; i++) {
        x = (b * (pow(i, a))) + c;
        if (i == digsum(x) && x < mod) {
            cout << x << " ";
        }
    }

    return 0;
}

In the case a,b,c = 3,2,8 respectively and i=19; pow(19,3) is supposed to calculate 19^3 but when I replace pow by (19x19x19), this specific case is getting satisfied, where as that wasn't the case with the pow function. Can someone explain what the problem is?

sidb2k
  • 3
  • 3

1 Answers1

0

My psychic powers suggest that your standard library's implementation of pow is not precise. I recall a discussion on SO a while back on this topic. Remember, pow returns a floating point value. I can't repro it, but it's entirely possibly your invocation of pow(19,3) returns 6858.999999999 or similar due to the way it's optimized.

Indeed, this this page says as much:

Due to rounding errors in floating point numbers, the results of pow() may not be precise (even if you pass it integers or whole numbers).

Also, this question and answer suggests the same thing.

I wouldn't have suspected it, but there you go.

Consider doing this as a workaround:

long long power = nearbyint(pow(i,a));
x = b * power + c;
selbie
  • 100,020
  • 15
  • 103
  • 173