ADVERTISEMENT
ADVERTISEMENT

Java - Greatest Common Divisor or Euclidean Algorithm Program or Highest Common Divisor

In this code snippet we will learn how to get Greatest Common Divisor in Java, Implementation of Euclidean Algorithm to get Highest Common Divisor.

The Euclidean algorithm is used to find the Greatest Common Divisor and Highest Common Divisor of two numbers. Greatest Common Divisor is calculated by divide both numbers with their common divisor.

Greatest Common Divisor / Euclidean Algorithm Program / Highest Common Divisor

public class Gcd {
    //  greatest common divisor
    public static int gcd(int First_number, int Second_number) {
        int i = First_number % Second_number;
            while (i != 0) {
            First_number = Second_number;
            Second_number = i;
            i = First_number % Second_number;
        }
        return Second_number;
    }
  
    public static void main(String[] args) {     
        Scanner sc=new Scanner(System.in);
 
        System.out.print("First Number  :");
        int num1=sc.nextInt();
        System.out.print("Second Number :");
        int num2=sc.nextInt();
 
        System.out.println("Greatest Common Divisors: " + gcd(num1,num2));
       
    }
}

Output

    First Number  :24
    Second Number :16
    Greatest Common Divisors: 8

Java Basic Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.