Skip to content

Instantly share code, notes, and snippets.

/pow!

Created September 16, 2012 00:12
Show Gist options
  • Save anonymous/3730474 to your computer and use it in GitHub Desktop.
Save anonymous/3730474 to your computer and use it in GitHub Desktop.
/* 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;
}
/* index of po2 works as follows:
val[0] is base ^ 2^0
val[1] is base ^ 2^1
val[2] is base ^ 2^2
...
val[i] is base ^ 2^i
*/
int power(int base, int exp) {
int *val = malloc(sizeof(int));
int *po2 = malloc(sizeof(int));
val[0] = 1;
po2[0] = 1;
val[1] = base*base;
po2[1] = 2;
po2[2] = 4;
int i = 2;
int expCounter = exp;
int result = 1;
do
{
val = realloc(val,i*sizeof(int));
val = realloc(val,(i+1)*sizeof(int));
val[i] = val[i-1] * val[i-1];
po2[i+1] = po2[i] * po2[i];
++i;
}while(expCounter - po2[i] >= 0);
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