Suppose I have an expression formed by integer variables and arithmetic operations: addition, subtraction and multiplication. I know that each multiplication takes M seconds, and each addition / substitution takes A seconds. Is there an algorithm that will evaluate an expression in the most efficient way for arbitrary assignment to variables? (Suppose I can only store one number in memory).
Example:
M = 10
A = 1
Expression: a * a + a * b + b * b.
Initially, it has 3 multiplications and 2 additions, so the total time is 3 * M + 2 * A = 32
However, we can construct the equivalent expression (a + b) * (a + b) -a * b, which has only 2 multiplications and 3 additions, so the total calculation time will be 2 * M + 3 * A = 23.
source share