Search code examples
c++theory

How would you write a program to reduce an equation?


I may be misinterpreting the exact phrasing on the question about which I've been thinking, but I'm curious as to how one would reduce an equation of multiple variables.

I'm assuming factoring plays a major role, however the only way I can think of doing it is to break the equation into a tree of operations and search the entire tree for duplicate nodes. I'm assuming that there's a better way, since many web applications do this quite quickly.

Any better way of doing this?


Solution

  • I would assume that the kind of reductions that they are looking for is that something like (2 + 3) * x should become (* 5 x) rather than (* (+ 2 3) x). In which case you can just recognize that subtrees are constant, and calculate them.

    You can also use the associative and commutative laws to try to move things around first to assist in the process. So that 2 + x + 3 would become (+ 5 x) rather than (+ (+ 2 x) 3).

    Take this idea as far as you want. It has been deliberately given in an open-ended fashion. I'm sure that they would be happy to see you automatically recognize that x * x + 2 * x + 1 is (* (+ 1 x) (+ 1 x)) instead of (+ (+ (* x x) (* 2 x)) 1) but you can do a lot of good reductions without going there.