Simplify or Reduce Fractions in Java

Zeeshan Afridi May 27, 2022
Simplify or Reduce Fractions in Java

In Mathematics, the fraction represents a part or portion of the whole. It has two parts, numerator and denominator, where the numerator is the dividend, and the denominator is the divisor.

Example: 500/1000 is a fraction equal to 1/2 and 0.5.

Simplify or Reduce Fractions in Java

There is always more than one way to achieve a task or goal in computer programming. But the best and most effective solution is the one with the following characteristics:

  1. concise and precise code
  2. has high performance
  3. has less space complexity

Fraction Example Code:

package articlecodesinjava;
class Fraction{

    public static long gcd(long x, long y) {
    return y == 0 ? x : gcd(y, x % y);
    }

public static String asFraction(long x, long y) {
    long gcd = gcd(x, y);
    return (x / gcd) + "/" + (y / gcd);
    }
}

class GuessingGame {
public static void main(String[] args){

    Fraction obj = new Fraction();  // Create the object of Fraction class

    System.out.println("Output");

    System.out.println(obj.asFraction(500, 1000));
    System.out.println(obj.asFraction(9, 3));
    System.out.println(obj.asFraction(11, 2));
    System.exit(0);
    }
}

Output:

Output
1/2
3/1
11/2
Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn

Related Article - Java Math