Beta Coder

Learn code like Beta Coder.

Breaking

Wednesday, September 23, 2020

JAVA Program to Find GCD or HCF of Two Numbers

Find GCD or HCF of Two Numbers

JAVA TO FIND GCD OR HCF OF TWO NUMBERS
In this program we learn how to calculate GCD or HCF of two numbers by provided user using Java.
Java program to calculate GCD or HCF of two numbers
// FIND GCD OR HCF OF TWO NUMBERS
import java.util.*;
class Gcd
{
	int a, b;
	public
		void getdata()
		{
			Scanner in = new Scanner(System.in);
			System.out.println("Enter two numbers : ");
			a = in.nextInt();
			b = in.nextInt();
		}
		int cgcd()
		{
			int r;
			do
			{
				r = a % b;
				a = b;
				b = r;
			}while(r != 0);
			return(a);
		}
		void display(int p)
		{
			System.out.println("The GCD = "+p);
		}
	public static void main(String arg[])
	{
		Gcd g = new Gcd();
		int p;
		g.getdata();
		p = g.cgcd();
		g.display(p);
	}
};
OUTPUT:
   Enter two numbers : 27 9
   The GCD = 9

No comments:

Post a Comment