Fraction in simplest form java

The program reduces the terms to their lowest values in a fraction. For example:

Enter numerator:
2500
Enter denominator:
50
Reduced form: 50/1

Enter numerator:
9
Enter denominator:
21
Reduced form: 3/7

Code:

import java.util.Scanner;

public class FractionReducer{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter numerator: ");
        int num = scan.nextInt();
        System.out.println("Enter denominator: ");
        int den = scan.nextInt();

        int smaller = num < den ? num : den;
        int HCF = -1;
        for (int i = smaller; i > 0; --i) {
            if (num%i==0&&den%i==0) {
                HCF = i;
                System.out.println("Reduced form: "+(num/HCF)+"/"+(den/HCF));
                break;
            }
        }
    }
}

No comments:

Post a Comment

any problem in any program comment:-

Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...