Subscribe Our Channel

header ads

Search This Blog

Friday, July 28, 2023

Java - Greatest Common Divisor or Euclidean Algorithm Program or Highest Common Divisor. | JAVA LANGUAGE | JAVA PROGRAMMING

 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.


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


    }

}

No comments:

Post a Comment

Featured Post

C++ Program to Create C++ Project to do Sunflower field with sky, cloud and sun

C++ Program to Create C++ Project to do Sunflower field with sky, cloud and sun HELLO VIEWERS YOU MIGHT BE INTERESTED IN THIS POST. Your wel...

Popular Posts