# to the nth power

Dolf Grunbauer dolf at idca.tds.PHILIPS.nl
Fri Nov 2 19:23:08 AEST 1990


In article <1990Nov1.232830.17131 at NCoast.ORG> catfood at NCoast.ORG (Mark W. Schumann) writes:
<int powi (int root, int exponent)
<{
<int i;
<int result = 1;
<  for (i = exponent; i > 1; i--) result *= root;
Oeps, I think this one ---^ should be a 0

<  return result;
<  }

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;
}
<Now you've gotta be careful about overflow here or use long ints.
<If you needed an integer version I hope this helps.
This is still true for my version as well, and also exponent must be >= 0;
-- 
   _ _ 
  / U |  Dolf Grunbauer  Tel: +31 55 433233 Internet dolf at idca.tds.philips.nl
 /__'<   Philips Information Systems        UUCP     ...!mcsun!philapd!dolf
88  |_\  If you are granted one wish do you know what to wish for right now ?



More information about the Comp.lang.c mailing list