It works perfectly except 5, when i give 5 it calculates wrong
No, it works perfectly for values less than 5
. When you give input 5
for both a
and n
, the summation resultant number will be 30517578125
which is big for 32
bit int
type variable to hold. Instead, you should use uint64_t
type variable.
Also, you should not use pow()
function for integer type. Check this.
You can do:
#include <stdio.h>
#include <inttypes.h>
int main()
{
int i, a, n;
uint64_t num = 1, result = 1;;
printf ("Enter a: \n");
scanf("%d",&a);
printf ("Enter n: \n");
scanf("%d",&n);
for(i = 0;i < n;i++){
num = num * a;
result = num * result;
}
printf("result: %"PRId64"\n", result);
return 0;
}
Note that this 64
bit solution is also having a limit and will work for input 5
but may not be for a number little bigger than 5
. If you want arbitrarily large number, check this.