top of page
Click here to go to the home page of AskTheCode.

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

Team ATC

Updated: Mar 9, 2021

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

 

Problem:

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:

3

 

Code:

import java.util.Scanner;

public class solution_GCD{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int a = sc.nextInt();
		int b = sc.nextInt();

		int gcd = get_GCD(a,b);

		System.out.println(gcd);
	}

	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);
	}
}

Recent Posts

See All

Comments


bottom of page