Implement *, -, and / operators using only +

Write a method to implement *, – , / operations You should use only the + operator.

My initial thoughts:
a * b can be implemented as adding a for b times.
a – b can be implemented as addition of a and -b.
a / b can be implemented as finding how many times you need to add b, until getting a.

My initial codes:

	public static int multiply(int a, int b) {
		int multiplier = (a < b ? a : b);
		int multiplicant = (multiplier == a ? b : a);
		int result = 0;
		for (int i = 0; i < multiplier; i = i + 1) {
			result = result + multiplicant;
		}
		return result;
	}

	public static int substract(int a, int b) {
		return a + (~b + 1);
	}

	public static int divide(int a, int b) {
		if (a == b)
			return 1;
		int result = 1;
		int mul = b;
		while (mul < a) {
			mul = mul + b;
			result = result + 1;
		}
		return result;
	}

Comments after running:
Two many errors.

  1. Multiplication and division can’t handle negative numbers!
  2. Division can only handle who quotient. For example, 8/3 will yield 3, which is wrong.
  3. Error condition of division: can’t divide by 0.

Revision (Solution):

	public static int negate(int number) {
		return ~number + 1;
	}

	public static int abs(int number) {
		return number < 0 ? negate(number) : number;
	}

	public static int multiply(int a, int b) {
		int multiplier = Math.min(abs(a), abs(b));
		int multiplicant = (multiplier == abs(a) ? abs(b) : abs(a));
		int result = 0;
		for (int i = 0; i < multiplier; i = i + 1) {
			result = result + multiplicant;
		}
		if (abs(a) == a) { // a >= 0
			if (abs(b) == b) // b >= 0
				return result;
			else
				// b < 0;
				return negate(result);
		} else { // a < 0
			if (abs(b) == b) // b >= 0
				return negate(result);
			else
				// b < 0;
				return result;
		}
	}

	public static int substract(int a, int b) {
		return a + negate(b);
	}

	public static int divide(int a, int b) {
		if (b == 0) {
			throw new java.lang.ArithmeticException("Divide by 0.");
		}

		int divident = abs(a);
		int divisor = abs(b);
		int quotient = 0;

		while (divident >= divisor) {
			divident = substract(divident, divisor);
			quotient = quotient + 1;
		}

		if (abs(a) == a) { // a >= 0
			if (abs(b) == b) // b >= 0
				return quotient;
			else
				// b < 0;
				return negate(quotient);
		} else { // a < 0
			if (abs(b) == b) // b >= 0
				return negate(quotient);
			else
				// b < 0;
				return quotient;
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: