Addition 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 29 30 31 | /*************************************************************************** * Author: Isai Damier * Title: Addition of Fractions * Project: geekviewpoint * Package: algorithms * * Statement: * Add the two given positive fractions * * Sample Input: {5,6}, {7,8}) * Sample Output: {41,24} * * Technical Details: * This is the same algorithm you learned in grade school: * 1) find the lowest common denominator, which is the same as finding * the lowest common multiplier of the given denominators. * 2) Convert the given fractions into equivalent fractions with the * new denominator * 3) add the numerators * 4) reduce the resulting fraction using the GCD (greatest common * divisor) of its numerator and denominator. * **************************************************************************/ public int [] addingFractions( int [] a, int [] b) { int denominator = LCM(a[ 1 ], b[ 1 ]); int numA = denominator / a[ 1 ] * a[ 0 ]; int numB = denominator / b[ 1 ] * b[ 0 ]; int numerator = numA + numB; int gcd = GCD(numerator, denominator); 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 | import org.junit.Test; import static org.junit.Assert.*; public class NumbersTest { /** * Test of addingFractions method, of class Numbers. */ @Test public void testAddingFractions() { System.out.println( "addingFractions" ); int [] a = { 5 , 6 }; int [] b = { 7 , 8 }; Numbers instance = new Numbers(); int [] expResult = { 41 , 24 }; int [] result = instance.addingFractions(a, b); assertArrayEquals(expResult, result); } } |