My intention was to show the way you can realize that but that's basically reinventing the wheel so not recommended. Here I have shown the rough idea of how you can try to write a power function.
Alternative way to realize that would be
int mpow(int b, int e) {
if (e <= -1) {
fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
exit(1);
}
if (e == 0) return 1;
if (b == 0) return 0;
int ans = 1;
for (int i = 1; i <= e; i++) {
if (!checkIfOverflown(ans, b)) ans = ans * b;
else {
fprintf(stderr, "%s\n", "overflow in multiplication");
exit(1);
}
}
return ans;
}
As pow
returns double
you shouldn't cast it to integer( why do you want to lose precision).
And why wrap pow
in function? You can use it directly.
Is my function correct?
This function is correct as long as the integer doesn't mess it up by spilling up things. For small value of b
,e
it works.
Also a simple more effective way to do this will be
int mpow(int b, int e) {
int res = 1, flag = 0;
if (e <= -1) {
fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
exit(1);
}
while (e > 0) {
if (e % 2 == 1) {
if (!checkIfOverflown(res, b))
res = (res * b);
else {
flag = 1;
break;
}
}
if (!checkIfOverflown(b, b))
b = (b * b);
else {
flag = 1;
break;
}
e /= 2;
}
if( flag ){
fprintf(stderr, "%s\n", "overflow in multiplication");
exit(1);
}
return res;
}