Re: how to specify power of number



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...

.



Relevant Pages

  • Re: RAD vs. performance
    ... whereas my compiler can optimize them ... optimise away your abstraction because you have thrown away the type ... check as effectively because you do not have the type information. ... away the unwanted abstraction that you have imposed upon us. ...
    (comp.lang.misc)
  • Re: RAD vs. performance
    ... underused and undersupported (by the compiler). ... away the unwanted abstraction that you have imposed upon us. ... the type int -> int and the type checker will unify this type with any ... equivalent to the case of your compiler being unable to optimise away ...
    (comp.lang.misc)
  • Re: RAD vs. performance
    ... be no slower than the specialized version, simply because the compiler ... so your compile times must go through the roof in order to optimise ... but they don't because you rarely need that abstraction. ... I'd have an int argument and generalise the result using ...
    (comp.lang.misc)
  • Re: RAD vs. performance
    ... compilers do nothing to optimise such code. ... maybe the OCaml people should improve their compiler:) ... OCaml code is not usually written in that form, ... It is a union type (an expression is ...
    (comp.lang.misc)
  • Re: AVR Beginner Questions - Ports and Speed
    ... On bigger processors, a good compiler will ... while the assembly programmer might use a full-blown divide ... > 3) One of the most productive strategies is to code in C, but optimise ... Chosing the optimal form for loops, ...
    (comp.arch.embedded)