# to the nth power
Mark W. Schumann
catfood at NCoast.ORG
Sat Nov 3 05:22:17 AEST 1990
In article <522 at ssp9.idca.tds.philips.nl> dolf at idca.tds.philips.nl (Dolf Grunbauer) writes:
> [I had written]:
>int powi (int root, int exponent)
>{
>int i;
>int result = 1;
> for (i = exponent; i > 1; i--) result *= root;
Dolf says:
>Oeps, I think this one ---^ should be a 0
Nope. I intended to leave out the iteration where you'd only be multiplying
by one.
>A quicker version (throw in a few registers if still not fast enough):
>int powi (int root, int exponent)
>{
> int result = 1;
>
> while (exponent > 0)
> {
> while (!(exponent & 1))
> {
> root *= root;
> exponent /= 2;
> }
> result *= root;
> exponent--;
> }
>
> return result;
>}
Spiffy, but it does depend on (exponent & 1) being the same as saying
"exponent is odd." Most implementations support this, though.
Again, neither solution supports negative exponents.
--
============================================================
Mark W. Schumann 3111 Mapledale Avenue, Cleveland 44109 USA
Domain: catfood at ncoast.org
UUCP: ...!mailrus!usenet.ins.cwru.edu!ncoast!catfood
============================================================
More information about the Comp.lang.c
mailing list