/** * Calculus with fractionals using gcd and lcm. * * @author (Stefan Edelkamp) * @version (2013) */ public class Fractional { /** * Euclid's algorithm * * @param a smaller of the two numbers * @param b larger of the two numbers * @return greatest common divisor of a and b */ public int gcd(int a, int b) { return a == 0 ? b : gcd(b%a,a); } /** * Exploiting Euclid's algorithm * * @param a smaller of the two numbers * @param b larger of the two numbers * @return least common multiplier of a and b */ public int lcm(int a, int b) { return a*b / gcd(a,b); } /** * Performing some calculatoins * * @param a nominator first fractional * @param b denominator first fractional * @param c nominator second fractional * @param d denominator second fractional * @return greatest common divisor of a and b */ public void compute(int a, int b, int c, int d) { System.out.println("(a/b)->("+(a/gcd(a,b))+"/"+(b/gcd(a,b))+")"); System.out.println("(c/d)->("+(c/gcd(c,d))+"/"+(d/gcd(c,d))+")"); int k = lcm(b,d); int s = a*k/b + c*k/d; System.out.println("sum = ("+(s/gcd(s,k))+"/"+(k/gcd(s,k))+")"); } }