How to rewrite an expression in order to have the result a multiple of X?

112 Views Asked by At

I'm a programmer and need to create an algorithm that takes any expression and rewrite it in a way that the final result is a multiple of a specific value X.

For example, let's consider that i need to get the double of a value, so X = 2 in all cases below:

F1: 3 + 5 = 8
F1(x2): 3*2 + 5*2 = 16

In this example, my original expression is a simple sum and if i multiply all operands by 2 i'll get the correct result (8*2 = 16).

Here are other examples:

F2: 3 * 5 = 15
F2(x2): = (3*5)*2 = 30

F3: 3*5 + 4*5 = 35
F3(x2): (3*5)*2 + (4*5)*2 = 70

F4: 3+4+5+6 = 18
F4(x2): 3*2 + 4*2 + 5*2 + 6*2 = 36

So far my algorithm is simple: every add/substract operand can be multiplied by X, and every multiplication/division result too.

But for a complex expression like the following, my solution will not generate the correct result.

F6: (10 * (5*2) +3 * (4+ 4*2 +4) *2) *3 = 588

So, how could i rewrite the F6 function in order to get the result 1176. Is it achievable?

EDIT

This is for a report system on which i have rows for each department and subtotals, so i may have some values that cannot be multiplied if present, for example:

employees/10

The value of emplyoees is dynamic and already given to me by the database i'm using, for all rows of the table and the substotal is already calculated, so my table is something like this:

row_type    counter     company_name    department_name     employees   ten_percent     twelve
data        1           A               A1                  10          1               12
data        1           A               A2                  15          1,5             12
data        1           A               A3                  10          1               12
subtotal    3           A                                   35          3,5             12
data        1           B               B1                  10          1               12
subtotal    1           B                                   10          1               12
total       4                                               45          4,5             12

Where counter is the X factor i refer to. "twelve" is the formula "12", so multiplying it by counter would result ok, but for complex formulas that may have dynamic values it would fail. So i'm looking to a way to change the expression, if possible, to make it work on any scenario.

Thanks.