In: Computer Science
Create a project called rise. Add a class called GCD. Complete a program that reads in a numerator (as an int) and a denominator (again, as an int), computes and outputs the GCD, and then outputs the fraction in lowest terms. Write your program so that your output looks as close to the following sample output as possible. In this sample, the user entered 42 and 56, shown in green.
Enter the numerator: 42
Enter the denominator:
56 The GCD is: 14
The fraction in lowest terms is: ¾
Use a while loop, in Java
import java.util.*;
public class GCD
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n,d,n1,n2;
//taking user inputs
System.out.print("Enter the numerator : ");
n=sc.nextInt();
System.out.print("Enter the denominator : ");
d=sc.nextInt();
assigning the values in separate variables
n1=n;
n2=d;
//while loop will execute until both values become equal
//the least value for this evaluation will be the GCD
while(n1!=n2)
{
if(n1>n2)
{
n1=n1-n2;
}
else
{
n2=n2-n1;
}
}
System.out.println("The GCD is : "+n2);
System.out.println("The fraction in lowest terms is : "+(n/n2)+"/"+(d/n2));
}
}
Create a project in Eclipse or in NetBeans with preferable name and then create java class file named as GCD.java ,save the above code in that and execute..