Home > Java, Mini-tips, Programación, snippets, Tips, Web > Simplify a fraction in Java

Simplify a fraction in Java

October 22, 2015 Leave a comment Go to comments


import java.util.*;
import java.io.*;

/**
* This method allows you to simplify a fraction
*
* @author grekz
* Sample input: 10 2
* Sample output: 5 1
**/
class Solution {

public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int A = in.nextInt();
int B = in.nextInt();

int gcd = findGCD(A, B);
System.out.println( gcd > 1 ? (A/gcd) + " " + (B/gcd) : A + " " + B);
}
private static int findGCD(int number1, int number2) {
return number2 == 0 ? number1 : findGCD(number2, number1%number2);
}
}

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: