Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!zaphod.mps.ohio-state.edu!sdd.hp.com!hplabs!hpda!hpwala!hpavla!gary From: gary@hpavla.AVO.HP.COM (Gary Jackoway) Newsgroups: comp.lang.c Subject: Re: # to the nth power Message-ID: <9130018@hpavla.AVO.HP.COM> Date: 2 Nov 90 13:49:41 GMT References: <90305.005050CJH101@psuvm.psu.edu> Organization: Hewlett-Packard Avondale Division Lines: 46 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