Search code examples
javafractions

How do I convert an improper fraction to a mixed number in Java?


I'm attempting the ccc j4 or s2 for the 2002 challenge. I currently have a function to simplify the fraction, but it gives it as a mixed number. The output of that function is a string, and I think I need another function to convert it into a mixed number. Any help would be appreciated. Thanks!

This is the function I used for converting:

public static long gcm(long a, long b) {
  return b == 0 ? a : gcm(b, a % b);
}

public static String asFraction(long a, long b) {
  long gcm = gcm(a, b);
  return (a / gcm) + "/" + (b / gcm);
}

It outputs an improper fraction, but I want a mixed number. How can I get this? P.S. English is not my first language.


Solution

  • Since this is part of a challenge, I'll refrain from providing the exact answer, but what I'd focus on is this: A mixed number is an integer followed by a proper fraction. You have an improper fraction. How do you convert improper fractions to mixed numbers?

    Let's take a simple example, say, 11/4. How would we write this as a mixed fraction? We'd write 2 3/4, because:

    • 2 is the largest integer smaller than 11/4.
    • 2 is 8/4, leaving 3/4 for the proper fraction.
    • Thus the integer part is 2 and the proper fraction is 3/4, giving us the answer.

    So, given an improper fraction n/d, one way to get a mixed number is to take k = floor[n/d], and return k + (n - kd)/d.

    Hope that helps!