Skip to content

Instantly share code, notes, and snippets.

@justjkk
Created June 30, 2010 16:49
Show Gist options
  • Save justjkk/458926 to your computer and use it in GitHub Desktop.
Save justjkk/458926 to your computer and use it in GitHub Desktop.
import java.io.*;
class Rational
{
/*
* Object oriented concept is misused here. Rational class doesn't need a
* isPrime() method. isPrime() should ideally come under the Integer class
*/
boolean isPrime(int n) // Java has boolean datatype
{
if(n < 2) // Remember, Prime numbers starts from 2
return false;
for(int j = 2; j * j <= n; j++) // It is enough to check from j=2 to j=sqrt(n)
{
if(n % j == 0)
return false;
}
return true;
}
/*
* Throwing exceptions out to the JVM environment is not a good habit.
*/
public static void main(String args[]) throws IOException
{
Rational o = new Rational(); // o is not a good identifier as it looks like 0
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//DataInputStream in = new DataInputStream(System.in);
String str, n1, n2;
int a, b, i, r1, r2, q1, q2, gcf; // q1 and q2 need not be set to zero; Small 'l' is not a good identifier as it resembles '1'.
System.out.print("Enter the rational number: ");
str = br.readLine();
for(i = 0; str.charAt(i) != '/'; i++); // A while loop with initialization and increment is better written as a for loop
n1 = str.substring(0,i);
n2 = str.substring(i+1);
a = Integer.parseInt(n1);
b = Integer.parseInt(n2);
q1 = a;
q2 = b;
if(q1<q2)
gcf = a;
else
gcf = b;
do
{
r1 = a%gcf;
r2 = b%gcf;
q1 = a/gcf;
q2 = b/gcf;
if(r1 != 0 || r2 != 0)
gcf--;
else
break;
}while(gcf != 0);
if(q2 == 1)
{
System.out.println("Output: "+q1);
}
else
{
System.out.println("Output: "+q1 + "/" + q2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment