Division of Fractions
by Isai Damier, Android Engineer @ Google
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /*************************************************************************** * Author: Isai Damier * Title: Division of Fractions * Project: geekviewpoint * Package: algorithms * * Statement: * Multiplication the two given fractions * * Sample Input: {-5,6}, {6,8}) * Sample Output: {-5,8} * * Technical Details: * This is the same algorithm you learned in grade school: * 1) cross multiply the numerators and the denominators * 4) reduce the resulting fraction using the GCD (greatest common * divisor) of its numerator and denominator. * **************************************************************************/ public int [] fractionDivision( int [] a, int [] b) { int numerator = a[ 0 ] * b[ 1 ]; int denominator = a[ 1 ] * b[ 0 ]; int num = 0 > numerator ? -numerator : numerator; int den = 0 > denominator ? -denominator : denominator; int gcd = GCD(num, den); gcd = 0 > gcd ? -gcd : gcd; return new int []{numerator / gcd, denominator / gcd}; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import org.junit.Test; import static org.junit.Assert.*; public class NumbersTest { /** * Test of fractionDivision method, of class Numbers. */ @Test public void testFractionDivision() { System.out.println( "fractionDivision" ); int [] a = new int [] { 8 , 5 }; int [] b = new int [] { 10 , 15 }; Numbers instance = new Numbers(); int [] expResult = { 12 , 5 }; int [] result = instance.fractionDivision(a, b); assertArrayEquals(expResult, result); a = new int [] { 5 , 6 }; b = new int [] { 6 , 8 }; expResult = new int []{ 10 , 9 }; result = instance.fractionDivision(a, b); assertArrayEquals(expResult, result); } } |