Java program to find HCF or GCD of two numbers | AskTheCode

Find the Greatest Common Divisor of two numbers in Java | Java Programming Solution | AskTheCode


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.

Input Format: A line containing two integers separated by a space.

Input Sample:

6 9

Output Format: A line containing an integer.

Output Sample:



import java.util.Scanner;

public class solution_GCD{

public static void main(String[] args) {

Scanner sc = new Scanner(;

int a = sc.nextInt();

int b = sc.nextInt();

int gcd = get_GCD(a,b);



public static int get_GCD(int a, int b){

if (a == 0)

return b;

if (b == 0)

return a;

if (a == b)

return a;

if (a > b)

return get_GCD(a-b, b);

return get_GCD(a, b-a);



7 views0 comments

Recent Posts

See All

Calculate BMI in Java | AskTheCode

Write a Java program that reads values for weight in kilograms and height in centimeters and prints out the BMI... interpretation of it...

"Believe you can and you're halfway there"