Commit c07f4256 by Fokion Zervoudakis

### Implement division by repeated subtraction.

parent 1ea207ff
src/math/Div.java 0 → 100644
 package math; import annotation.Math; class Div { /** Uses repeated subtraction to calculate the quotient of Euclidean division. @param a the dividend @param b the divisor @return the quotient of {@code a / b} */ @Math int quo(int a, int b) { if (b == 0) { throw new ArithmeticException(); } int q = 0; while (a >= b) { a -= b; q++; } return q; } /** Uses repeated subtraction to calculate the remainder of Euclidean division. @param a the dividend @param b the divisor @return the remainder of {@code a / b} */ @Math int rem(int a, int b) { if (b == 0) throw new ArithmeticException(); while (a >= b) { a -= b; } return a; } }
 package math; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; class DivTest { private Div div; @BeforeEach void beforeEach() { div = new Div(); } @Test void itCalculatesTheQuotient() { assertEquals(0, div.quo(0, 1)); assertEquals(1, div.quo(1, 1)); assertEquals(4, div.quo(12, 3)); assertEquals(4, div.quo(13, 3)); assertEquals(5, div.quo(25, 5)); assertEquals(5, div.quo(27, 5)); } @Test void itCalculatesTheRemainder() { assertEquals(0, div.rem(0, 1)); assertEquals(0, div.rem(1, 1)); assertEquals(0, div.rem(12, 3)); assertEquals(1, div.rem(13, 3)); assertEquals(0, div.rem(25, 5)); assertEquals(2, div.rem(27, 5)); } @Test void itDoesNotDivideByZero_quo() { try { div.quo(0, 0); fail(new Throwable()); } catch (ArithmeticException ignored) { } } @Test void itDoesNotDivideByZero_rem() { try { div.rem(0, 0); fail(new Throwable()); } catch (ArithmeticException ignored) { } } }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!