Connecting Tech Pros Worldwide Forums | Help | Site Map

i need help in writing a power function..

Newbie
 
Join Date: Jan 2007
Posts: 29
#1: Jan 17 '07
hi
i need help in writing a function
integerPower(base,exponent) that returns the value base^exponent with assuming that the exponent is a positive, nonzero integer and that the base is an integer. the function integerPower should use for or while loop to control the calculations, without using any math library functions.

Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#2: Jan 17 '07

re: i need help in writing a power function..


Think about what an exponent is. If I want, say, 3^7, that's 3*3*3*3*3*3*3. Generalize this for x^y, and you'll have your algorithm.
Familiar Sight
 
Join Date: Aug 2005
Location: Houston, TX
Posts: 143
#3: Jan 21 '07

re: i need help in writing a power function..


The nice thing about this is that your function will be _much_ faster than using the built-in pow( double,double ) function. You'd be amazed at the improvement in performance in graphics code when changing from something like
Expand|Select|Wrap|Line Numbers
  1. pow( x,2 ) + pow( y,2 )
to something like this
Expand|Select|Wrap|Line Numbers
  1. intpow(x,2) + intpow(y,2)
or better yet, since x^2 is used so frequently, make an inline function just for squares:
Expand|Select|Wrap|Line Numbers
  1. square(x) + square(y)
In some of my graphics and scientific computations, I've found enormous performance gains just from not using the built-in pow() function. This makes sense, since they probably use a Taylor series expanstion to deal with the genera case of a decimal power. -- Paul
Newbie
 
Join Date: Jan 2007
Posts: 29
#4: Jan 21 '07

re: i need help in writing a power function..


thx alot..i appreciate ur help..and thx for the hint too..it is a new piece of information..
Reply