Exercise: Hard Mode Math

Write a console program that reimplements a few mathematical operations using methods:

Don't use the built-in operators *, /, % or the method Math.pow in your program. Instead, use only addition, subtraction, and your own methods to implement these operations.

You don't need to deal with negative operands in your implementation, but you can for extra credit.

Here is some example code that shows how these methods could be used:

int multiplier = 3;
int multiplicand = 8;
int product = mult(multiplier, multiplicand);
System.out.println(multiplier + "*" + multiplicand + " = " + product);

int dividend = 5;
int divisor = 2;
int quotient = quot(dividend, divisor);
System.out.println(dividend + "/" + divisor + " = " + quotient);

int remainder = rem(dividend, divisor);
System.out.println(dividend + "%" + divisor + " = " + remainder);

dividend = 7005;
divisor = 7;
remainder = rem(dividend, divisor);
System.out.println(dividend + "%" + divisor + " = " + remainder);

dividend = 5;
divisor = 0;
quotient = quot(dividend, divisor);
System.out.println(dividend + "/" + divisor + " = " + quotient);

int baseNum = 2;
int exponent = 6;
int power = exponentiate(baseNum, exponent);
System.out.println(baseNum + "^" + exponent + " = " + power);

baseNum = 2;
exponent = 0;
power = exponentiate(baseNum, exponent);
System.out.println(baseNum + "^" + exponent + " = " + power);
Output:
3*8 = 24
5/2 = 2
5%2 = 1
7005%7 = 5
Error: Divisor cannot be zero
5/0 = 0
2^6 = 64
2^0 = 1
Division by zero is not defined mathematically. In your program, you can print an error message and return 0 if the divisor is 0.

Hand in instructions

  1. Make sure your program runs correctly.
  2. Hand in your program by uploading Main.java to Moodle.