This is the same as math.h's pow() function. You might find this useful if math.h is unavailable or you're working with some unusual data type. At the very least it's just interesting to see how it's done.
Code:
int powx(int x, int y) // calculates x^y
{
int base=x, res=1;
while(y)
{
if(y&1)
res *= base;
y>>=1;
base *= base;
}
return res;
}
Usage:
main() {
powx(5, 2) // would return 25
}
Extensions:
Sources:
http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int
Comments (0)
You don't have permission to comment on this page.