# to the nth power
Gary Jackoway
gary at hpavla.AVO.HP.COM
Sat Nov 3 00:49:41 AEST 1990
Mark W. Schumann writes:
> If you are interested in an integer version of the same function, try this:
> int powi (int root, int exponent)
> {
> int i;
> int result = 1;
> for (i = exponent; i > 1; i--) result *= root;
> return result;
> }
> Now you've gotta be careful about overflow here or use long ints.
> If you needed an integer version I hope this helps.
If you're going to post C code, you might TEST it! Clearly it should
be "i > 0" in the for statement, not "i > 1".
Also, this function gives the wrong result for negative powers.
(Granted, you rarely want to pass this function negative powers,
but it ought to work correctly.)
Further, there is a substantially faster way to do this:
int powi (int root, int exponent)
{
int i;
int result = 1;
int pow = root;
if (exponent < 0) {
if (root==1 || root==-1)
return powi(root,-exponent);
return 0;
}
for (i = exponent; i > 0; i = i>>1) {
if (i&1) result *= pow;
pow *= pow;
}
return result;
}
The first "if {}" makes sure we always get the right value for negative
exponents. The "for" loop runs for only as many iterations as the highest
bit in the exponent. Note that the actual loop is only one line longer
than the slower method.
Gary Jackoway
More information about the Comp.lang.c
mailing list