Description
Since you can apply the @fastpow
macro to a whole block of code, in principle it could recognize when you are computing multiple powers (e.g. x^2
, x^5
, and x^7
) of a single variable, and then compute an optimal set of multiplications for the set, sharing operations wherever possible.
Finding the truly optimal set of multiplications is NP-complete, though, and I'm not sure if there is a good way to precompute and tabulate it like we do for a single exponent. But we could certainly compute a near-optimal set of multiplications using a variant of the power-by-squaring algorithm.
You would also have to be careful to identify when a given variable x
refers to the same value at multiple points in the code, which is a bit hard to do at the macro level where types are unknown (so we can't be certain which operations might mutate x
).