Monday, July 14, 2014

Program for reducing fractions to lowest terms [Java]

So this is just some random program given as a programming exercise by a friend of mine - Saksham. He is pretty excited about his new website.

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