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

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:
- concise and precise code
- has high performance
- 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
Author: Zeeshan Afridi
Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.
LinkedInRelated Article - Java Math
- Probability in Java
- Find Factors of a Given Number in Java
- Evaluate a Mathematical Expression in Java
- Calculate the Euclidean Distance in Java
- Calculate Distance Between Two Points in Java