The GCD
by CodeChum Admin
The greatest common divisor, also known as GCD, is the greatest number that will, without a remainder, fully divide a pair of integers.
Now, I want you to make a program that will accept two integers and with the use of loops, print out their GCD. Make good use of conditional statements as well.
Off you go!
Input
A line containing two integers separated by a space.
6·9
Output
A line containing an integer.
3
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Creating an object of BufferedReader class
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
// Array of string type to store input
String[] gcd_numbers;
//propmt the use to enter the two numbers separated by space
System.out.print("\nEnter the two numbers separated by space: ");
gcd_numbers = input.readLine().split(" ");
int first_number = Integer.parseInt(gcd_numbers[0]);
int second_number = Integer.parseInt(gcd_numbers[1]);
// initially set to gcd
int gcd = 1;
for (int i = 1; i <= first_number && i <= second_number; ++i) {
// check if i perfectly divides both n1 and n2
if (first_number % i == 0 && second_number % i == 0)
gcd = i;
}
System.out.println("\nGCD of " + first_number +" and " + second_number + " is " + gcd);
}
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment