Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!uakari.primate.wisc.edu!uflorida!ukma!usenet.ins.cwru.edu!ncoast!catfood From: catfood@NCoast.ORG (Mark W. Schumann) Newsgroups: comp.lang.c Subject: Re: # to the nth power Summary: Yet another algorithm... Keywords: Powers Integers Message-ID: <1990Nov2.182217.13958@NCoast.ORG> Date: 2 Nov 90 18:22:17 GMT References: <9750@helios.TAMU.EDU> <1990Nov1.232830.17131@NCoast.ORG> <522@ssp9.idca.tds.philips.nl> Sender: catfood@ncoast.org (Mark W. "Catfood" Schumann) Organization: Random Lines: 45 In article <522@ssp9.idca.tds.philips.nl> dolf@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@ncoast.org UUCP: ...!mailrus!usenet.ins.cwru.edu!ncoast!catfood ============================================================