This is the seventh part of the ILP series. For your convenience you can find other parts in the table of contents in Part 1 – Boolean algebra
We have already seen how to multiply variables in ILP. In part 5 we saw how to define minimum and absolute value. Last time we improved our multiplication algorithm. Today we are going to handle negative numbers.
First let’s summarize what we can do already:
- We are able to decompose variable and extract its digits
- We can multiply two binary digits by calculating their conjunction
- We know how to multiply non-negative number by single binary digit using minimum function
- We can multiply two non-negative numbers by decomposing latter argument, multiplying its digits by former argument and power of two, and summing the results
- We know how to compare numbers and so we are able to deduce whether a number is negative (by comparing it with zero)
We would like to multiply possibly negative numbers. We will do that by multiplying their absolute values (so ignoring the sign) and then changing the sign if necessary.
First step – multiplying absolute values
We start with the following variables:
We have arguments (), result (), upper bound (), and digits of . We first define:
Here we multiply variables by using already described algorithms.
Second step – calculating the sign
Next, we calculate the sign:
will be one only when and have the same sign (so they are both negative or both positive). When the arguments have different signs, will be equal to zero.
Final step – changing the sign of the result
Now we are going to set the sign of the result. We multiply the result of multiplication of absolute values by the sign:
When the sign is equal to one the will be equal to . Otherwise, it will be equal to zero.
Now we are going to set the final result using this formula:
When the result should be non-negative, the sign will be equal to one, so the will be equal to , and we will get . However, when the result should be negative, the sign will be zero, the will be equal to zero, and we will get .
We are now able to multiply any integer variables for which we know upper and lower bound. In the next part we will use this operation to calculate greatest common divisor (GCD).