Re: how to specify power of number
- From: Antoninus Twink <nospam@xxxxxxxxxxxxxx>
- Date: Fri, 18 Apr 2008 23:23:02 +0200 (CEST)
On 18 Apr 2008 at 14:05, Yanb wrote:
Antoninus Twink <nospam@xxxxxxxxxxxxxx> wrote:
For general integer powers, a simple square-and-multiply algorithm is
a good bet, e.g.
unsigned long long power(unsigned a, unsigned b)
{
unsigned long long r, bit, pow;
for(bit=r=1, pow=a; bit<=b; bit<<=1, pow *= pow)
if(b & bit)
r*=pow;
return r;
}
The hardest part is checking for overflow - left as an exercise for
the reader...
Thank you both. I must admit, that the code Is almost a mystery for me :-)
Well, it's overkill for exponents small enough not to overflow a
unit64_t, but the idea is this: naively, to raise a to the power b takes
b integer multiplies (a*a*...*a, b times). But actually, you can do this
using more like log(b) multiplies by repeatedly squaring to compute a^2,
a^4, a^8, ... and then multiplying those terms corresponding to
exponents of 2 that occur in the binary expansion of b. For example, if
b=7, then a^7 = a^(1+2+4) = a * a^2 * a^4.
.
- Follow-Ups:
- Re: how to specify power of number
- From: user923005
- Re: how to specify power of number
- References:
- how to specify power of number
- From: Yanb
- Re: how to specify power of number
- From: Bartc
- Re: how to specify power of number
- From: Antoninus Twink
- Re: how to specify power of number
- From: Yanb
- how to specify power of number
- Prev by Date: Re: compile errors. pls help
- Next by Date: Re: how to specify power of number
- Previous by thread: Re: how to specify power of number
- Next by thread: Re: how to specify power of number
- Index(es):
Relevant Pages
|