Problem Statement:
The greatest common divisor (GCD) of two integers is the largest integer that evenly divides the two numbers. Write method gcd that returns greatest common divisor of two integers. Incorporate the method into an application that reads two values from user and displays the result.
Input and Output Requirements:
The program accepts two numbers through the keyboard as input. It will find the greatest common divisor of the two numbers and displays the result.
Algorithm:
Begin
Input the two numbers a and b
Calculate GCD c
While a mod b not equal to zero
c= a mod b
a=b
b=c
Display the result c
End
Program:
import java.io.*; import java.*; import java.util.*; Public class gcd { public static void main(String args[]) { Calculation c = new Calculation(); c.Input(); c.gcdCalc(); } } class Calculation { int First,Second,temp; Scanner input = new Scanner(System.in); void Input() { System.out.print("Enter first number:"); First = input.nextInt(); System.out.print("Enter Second number:"); Second = input.nextInt(); } void gcdCalc(){ int rem = 0; if(First < Second) { int t; t= First; First = Second; Second = t; } while(Second != 0) { rem = First % Second; First = Second; Second =rem; } System.out.print("The GCD is:"+ First); } } |
Output
Enter first number:15
Enter Second number:20
The GCD is:5
Enter first number:2
Enter Second number:5
The GCD is:1