/* * UnitFraction : * Accept input from the user a fraction between 0 and 1 (non-inclusive). * Find a decomposition of the fraction into a sum of unit fractions. * A unit fraction simply is a fraction with a numerator of one. * * Interestingly, there always exists such a (finite) sum of unit * fractions that is equivalent to any given fraction. * * E.g., 5/6 = 1/2 + 1/3 * 13/87 = 1/7 + 1/153 + 1/31059. * * The decomposition into unit fractions is not necessarily unique. * That is, there may be several different sums that work. * * One algorithm that will always find us a unit fraction sum * for our fraction is by Fibonacci. * * Find the largest unit fraction (so smallest denominator) that * is smaller than, or equal to our fraction. * * Print out this unit fraction. * * Subtract it from our fraction. * * If our fraction is now zero, we are done! * Otherwise, repeat the process. * * This is guaranteed to finish. * * Parke Godfrey * 2009 October 20 */ import java.io.PrintStream; import java.util.Scanner; import type.lib.Fraction; public class UnitFractionA { public static void main(String[] useless) { Scanner input = new Scanner(System.in); PrintStream output = System.out; output.println("Enter a positive fraction " + "(numerator denominator):"); Fraction frac = new Fraction(input.nextLong(), input.nextLong()); boolean first = true; // While not zero... while (!frac.equals(new Fraction(0, 1))) { // Find the largest unit fraction smaller than, or equal to, // frac. One way to do this is to start with 1/2. If too big, // then consider 1/3. Still too big, then 1/4. And so on. Fraction unit = new Fraction(1, 2); while (unit.compareTo(frac) > 0) { unit = new Fraction(1, unit.getDenominator() + 1); } // Do not print a leading "+" the first time through. if (first) { first = false; } else { output.print(" + "); } output.print(unit); frac.subtract(unit); } output.println("."); } }