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

  • Want to organize your cloud files? Sign up for a free webinar to see how Dokkio (a new product from PBworks) can help you find, organize, and collaborate on your Drive, Gmail, Dropbox, and Slack files: Weds, May 27 at 2PM Eastern / 11AM Pacific
View
 

Powx

Page history last edited by Kenneth Finnegan 11 years, 8 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.