# Operations

**16.9 Operations:**Write methods to implement the multiply, subtract, and divide operations for integers. The results of all of these are integers. Use only the add operator.

- The key to this problem was to try and simplify as much as possible the operators using other operators. For example, subtraction is addition negated. Multiplication is stacking up addition. Division is just counting the amount of times you can subtract a number.
- So when we define negate, we immediately can define subtraction.
- With subtraction we can immediately define division.
- Multiplication can be defined immediately on its own. I use xor to know when I have to negate.

- One flaw I have right now is with the negate and absNew, because they rely on eachother - they get into an infinite loop - so I've had one of them use the the real abs. Edit: one solution to this would be to negate a number by flipping its MSB.

int negate(int a) {

return ~a + 1;

}

int absNew(int a) {

if (a < 0) {

return negate(a);

}

return a;

}

int sub(int a, int b) {

// a - b = a + (-1)*b

return a + negate(b);

}

int mult(int a, int b) {

// one is negative

if (b < 0 ^ a < 0) {

int sum = 0;

for (int i = 0; i < absNew(b); i++) {

sum += absNew(a);

}

// negate

return negate(sum);

}

// other wise both are negative, or both are positive

// do the same thing without negating

else {

int sum = 0;

for (int i = 0; i < absNew(b); i++) {

sum += absNew(a);

}

return sum;

}

}

int divide(int a, int b) {

if (!b) {

cout << "Cannot divide by zero" << endl;

return INT_MAX;

}

// a / b = a * 1/b or the amount of times b can fit into a

int times = 0;

int b_cpy = b;

// if either is negative, negate the final result

if (a < 0 ^ b < 0) {

a = absNew(a);

b = absNew(b);

while (absNew(a) >= 0) {

int sub_ = sub(a, b);

if (sub_ < 0) return negate(times);

else {

a -= b;

times++;

}

}

}

else {

a = absNew(a);

b = absNew(b);

while (absNew(a) >= 0) {

int sub_ = sub(a, b);

if (sub_ < 0) return times;

else {

a -= b;

times++;

}

}

}

}

int main()

{

cout << absNew(-7) << endl;

cout << absNew(100) << endl;

cout << absNew(0) << endl;

pause();

cout << negate(-7) << endl;

cout << negate(100) << endl;

cout << negate(0) << endl;

pause();

cout << sub(7, 6) << endl;

cout << sub(100, -3) << endl;

cout << sub(-400, 473) << endl;

cout << sub(-23, -3) << endl;

cout << sub(0,0) << endl;

pause();

cout << mult(7, 6) << endl;

cout << mult(100, -3) << endl;

cout << mult(-400, 473) << endl;

cout << mult(-23, -3) << endl;

cout << mult(0, 0) << endl;

pause();

cout << divide(7, 6) << endl;

cout << divide(100, -3) << endl;

cout << divide(-400, 473) << endl;

cout << divide(-23, -3) << endl;

cout << divide(0,0) << endl;

pause();

}

Last modified 4yr ago