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};
}