by SapphireSun · 11y ago · 0 comments
fn pow(x, n): exp( n * ln(x) )
This is how you assure that power operations take constant time regardless of the input. However, exp and ln are relatively slow in numerical computing land, so if you're using small powers simply doing the multiplication out or if you're using powers of two, bit shifting will be faster.* Why is constant time desirable here, if the operation can be quicker for some inputs?
x^6 = x * x * x * x * x // linear in n
Here's a slightly (probably slightly wrong) optimized version of that which is O(log(n)):
fn pow(x, n):
if n == 0: 1
elif n == 1: x
elif n is even:
return pow(x * x, n/2)
elif n is odd:
return x * pow(x * x, (n-1)/2)
The nice thing is about the constant time is that it's relatively speedy (< 1ms) and is guaranteed to handle even large inputs gracefully[1]. Some implementations might add an additional optimization like if n == 2: x * x or n == 3: x * x * x since those are super common, but if you're really crunched, you've added if statements or function calls when you could have just inlined it.[1] Though you'll start running into quantization error at some point from ln.