| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Get control of your email attachments. Connect all your Gmail accounts and in less than 2 minutes, Dokkio will automatically organize your file attachments. You can also connect Dokkio to Drive, Dropbox, and Slack. Sign up for free.

View
 

Powx

Page history last edited by Kenneth Finnegan 11 years, 9 months ago

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.