-
-
Save JAChapmanII/3730513 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* index of po2 works as follows: | |
po2[0] is base ^ 2^0 | |
po2[1] is base ^ 2^1 | |
po2[2] is base ^ 2^2 | |
... | |
po[i] is base ^ 2^i | |
*/ | |
int power(int base, int exp) { | |
int n = (exp+1)/2; | |
int *val = calloc(n,sizeof(int)); | |
int *po2 = calloc(n,sizeof(int)); | |
val[0] = 1; | |
po2[0] = 1; | |
val[1] = base*base; | |
po2[1] = 2; | |
int i; | |
int expCounter = exp; | |
int result = 1; | |
for(int j = 2; j < n; ++j) | |
{ | |
val[j] = val[j-1] * val[j-1]; | |
po2[j] = po2[j-1] * po2[j-1]; | |
} | |
i = n - 1; | |
while(expCounter > 0) | |
{ | |
if(expCounter % 2 == 0) | |
{ | |
if(expCounter - po2[i] >= 0) | |
{ | |
result*=val[i]; | |
expCounter-=po2[i]; | |
} | |
--i; | |
}else | |
{ | |
result*=base; | |
--expCounter; | |
} | |
} | |
free(val); | |
free(po2); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment