Re: how to specify power of number
- From: Yanb <Yanb@xxxxxxxxxxxxxxxx>
- Date: Fri, 18 Apr 2008 16:05:35 +0200 (CEST)
Antoninus Twink <nospam@xxxxxxxxxxxxxx> wrote in
news:slrng0h483.166.nospam@xxxxxxxxxxxxxx:
On 18 Apr 2008 at 11:01, Bartc wrote:
You would have to use pow(256,3) which uses floating point arithmetic
-- not recommended, even though the compiler is likely to optimise.
Your code is fine as it is, the compiler will optimise 256*256*256 to
*16777216 or <<24. Or just write those in yourself.
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 :-)
.
- Follow-Ups:
- Re: how to specify power of number
- From: Antoninus Twink
- 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
- how to specify power of number
- Prev by Date: Re: pointer to string
- 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
|