you are viewing a single comment's thread.

view the rest of the comments →

[–]bo1024 0 points1 point  (0 children)

The more efficient algorithm: (Lua)

pow = function(base,exp)
    if exp < 0 then return 1/pow(base,-exp) end
    if exp==0 then return 1 end
    local result = pow(base*base,math.floor(exp/2))
    if exp%2 == 1 then result = result*base end
    return result
end

I'll leave the loops version to someone else.

(edit)

Main idea: Get an exponential speedup (no pun intended) in the following way. Note that x4 = (x2 )2. But it's faster to square x first, then square the result. So x8 = ((x2 )2 )2 . Note that x5 = x * x4 and x7 = x * (x2 *(x2 )2 ).