Re: how to specify power of number
- From: Antoninus Twink <nospam@xxxxxxxxxxxxxx>
- Date: Fri, 18 Apr 2008 14:16:02 +0200 (CEST)
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...
.
- Follow-Ups:
- Re: how to specify power of number
- From: Yanb
- 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
- how to specify power of number
- Prev by Date: Re: pointer to string
- Next by Date: Re: C++, C#, C Excellent site!!!
- Previous by thread: Re: how to specify power of number
- Next by thread: Re: how to specify power of number
- Index(es):
Relevant Pages
|