# to the nth power

Rory Jacobs rory at maccs.dcss.mcmaster.ca
Fri Nov 2 12:58:25 AEST 1990


In article <1990Nov1.232830.17131 at NCoast.ORG> you write:
>In article <9750 at helios.TAMU.EDU> randy at cs.tamu.edu (Randy Hutson) writes:
>>In article <15984 at mentor.cc.purdue.edu-> edgincd2 at mentor.cc.purdue.edu (Chris Edgington *Computer Science Major*) writes:
>>->In article <90305.005050CJH101 at psuvm.psu.edu->, CJH101 at psuvm.psu.edu (Carl J. Hixon) writes:

[
  Lots of methods for computing a raised to the power n deleted
]

Oh well, I *mailed* everything said in the above articles to the original
poster.  But the last one (iterative computation of a^n) makes me post the
following version:

int power2 (x,n)
/* note that x, p, sqp if made type double this would allow
 * x^n for real numbers x and integers n.  This just does integers  
 * x raised to the intger powers 
 */

int x;
int n;
{
   int p = 1.0;
   int sqp = x;
   int i=n;

   while (i>0) {
      if ((i % 2) == 1) p *= sqp;
      sqp *= sqp;
      i = i / 2;
   }
   return(p);
}

This calculates x^n and run in O(log2 n) time...

  Rory "Bug Slayer" Jacobs
  rory at maccs.dcss.mcmaster.ca



More information about the Comp.lang.c mailing list