Q:

Write a Java Program to find GCD (HCF) of Two Numbers

belongs to collection: Java Basic Solved Programs

0

The greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that is a divisor of both numbers.

For example, the GCD of 8 and 12 is 4.

This is java program to find the gcd of given two numbers. GCD is calculated using Euclidean Algorithm.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

  • Here is the source code of the Java Program to Find the GCD of 2 Numbers. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

SOURCE CODE ::

import java.util.Scanner;

public class GCD {
    
    public static void main(String[] args) {
        
        int a,b,gcd,temp1,temp2;
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter 1st No.");
        a=sc.nextInt();
        System.out.println("Enter 2nd No.");
        b=sc.nextInt();
        
        temp1=a;
        temp2=b;
        
                while(true)
                {
                    if(a>b)
                    {
                            if(a%b==0)
                            {
                                gcd=b;
                                break;
                            }
                            else
                            {
                                a=a%b;
                            }
                    }
                    else
                    {
                            if(b%a==0)
                            {
                                gcd=a;
                                break;
                            }
                            else
                            {
                                b=b%a;
                            }
                    }
                }
        
        System.out.println("GCD of "+ temp1 +" and "+ temp2 +" = "+ gcd);
    }
    
}

OUTPUT ::

Enter 1st No.
24
Enter 2nd No.
60
GCD of 24 and 60 = 12

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Solved Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java Program to Check whether Given Number is Arms... >>
<< Write a Java Program to display Fibonacci Series u...