ccalculationpowmodulo

Operation on a variable and constant giving different result in c


A simple calculation: 3^20%15.
The answer, according to a calculator, is 6.

The following code generates answer 7.

#include <stdio.h>
#include <math.h>
int main() {
        int i = 20;
        printf("%d\n", ((int)pow(3,20)%15));
        return 0;
}

If I replace 20 in the printf statement with the variable i, it gives -8 as output.

Assuming that the calculator is correct (or not?), what is the problem in the program?


Solution

  • The result of pow(3,20) can't fit in an int on your platform (or mine for that matter). Because of that, you're experiencing unexpected results.

    Changing to a larger integer type such as long long will do the job.

    Moreover, pow works with floating-point numbers which aren't represented exactly in memory (look that up). During conversion to an integer, that can cause certain errors. For example, for printf("%fl\n", (pow(3,20))); I get 3486784401.000000l which is not a precise integer value.