top

Search

Java Tutorial

.

UpGrad

Java Tutorial

GCD of Two Numbers in Java

Introduction

The greatest common divisor (GCD) or greatest common factor (GCF) is the highest possible divisor of two or more numbers.

To find out the GCD for different sets of numbers manually is a tedious process. However, finding GCD for two numbers in Java is pretty straightforward.

Overview

A Java program to determine the GCD of two or more numbers has multiple applications in various domains, such as cryptography, data encryption, and algorithm design.

Right from the basic Java loops to determine the GCD to the Euclidean algorithm, this tutorial aims at indulging you in all the concepts related to calculating the GCD of two numbers in Java.

How to Find the Greatest Common Factor  

To find the Greatest Common Factor manually, you must first separate each number in the set. So how to find the GCD of two numbers?

For example, 18 and 27. 

Now list the factors of these numbers. 

Factors of 18: 1, 2, 3, 6, 9, 18

Factors of 27: 1, 3, 9, 27

Now identify the common factors of the lot. They are 1, 3, and 9. Of these, 9 is the greatest number. Hence the GCD of 18 and 27 is 9.

The process is similar to finding the GCD of n numbers in Java, where n is any number greater than 1. 

For example, 21, 42, and 54.

Factors of 21: 1, 3, 7, 21

Factors of 42: 1, 2, 3, 6, 7, 14, 21, 42

Factors of 54: 1, 2, 3, 6, 9, 18, 27, 54

Now identifying the common factors: 1, 3.

So the GCD of 21, 42, and 54 is 3.

Algorithm to Find GCD  

Here are some different methods you can use to find the GCD of two numbers:

Using Java ‘while’ Loop

Loops in Java are repetitive paradigms that run under conditions specified by the user. There are three major kinds of loops in Java:-

i)  “for” loop

ii)  “while” loop

iii) “do-while” loop

Using User-Defined Method

The user can also define a customized method within the class to calculate the GCD.

Using the Euclidean Algorithm

The Euclidean algorithm is one of the most effective ways of finding the GCD of two numbers. The algorithm works under the following conditions:

1. Suppose the two numbers whose GCD we are supposed to find out are x and y. 

2. If x=0, method GCD(x,y) = y, and the syntax returns y as the GCD.

3. If y=0, method GCD(x,y) = x, and the syntax returns x as the GCD.

4. Now if neither x nor y equals 0, the algorithm proceeds to the long division method where Q is the quotient and R is the remainder.

5. x= Qy + R.

6. Now find GCD (y, R) using the above steps again until one of them becomes 0.

Using Modulo Operator

Using the modulo operator simplifies finding the GCD, determining whether one number is divisible by another without explicitly dividing them. We can efficiently find the GCD of the two numbers by repeatedly applying the modulo operation and updating the values. 

You can follow these steps to find the GCD of two numbers in Java using the modulo operator:

1. Start with two given numbers: x and y.

2. Take the modulo (remainder) of x divided by y using the % operator.

  • If the remainder R is 0, then y is the GCD of the two numbers.

  • If the remainder R is not 0, proceed to the next step.

3. Set x equal to y, and y equal to R obtained in the previous step.

4. Repeat the steps until the remainder is 0.

5. Once the remainder becomes 0, the last non-zero remainder obtained will be the GCD of the two numbers.

Find the GCD of Two Numbers Using for Loop and if Statement  

Here is a program to find the GCD of two numbers that will help you understand the use of the “for” loop:

public class GCDExample {
    public static void main(String[] args) {
        int number1 = 36;
        int number2 = 48;
        int gcd = 1;
        // Find the smaller number between number1 and number2
        int smallerNumber = (number1 < number2) ? number1 : number2;
        // Iterate from 1 to the smaller number
        for (int i = 1; i <= smallerNumber; i++) {
            // Check if both number1 and number2 are divisible by i
            if (number1 % i == 0 && number2 % i == 0) {
                gcd = i; // Update gcd
            }
        }
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
    }
}

In this example, we have the same numbers, number1, and number2, whose GCD must be found. The gcd variable is initialized to 1.

Similar to the previous example, we find the smaller number between number1 and number2 using the ternary operator and assign it to the smallerNumber variable.

Next, we initialize a variable i to 1 before entering the while loop. Within the loop, we check if number1 and number2 are divisible by i. If they are, we update the gcd variable to i. After that, we increment i by 1 using i++.

The loop continues until i exceeds the smallerNumber value. Once the loop terminates, we print the GCD of the two numbers using the System.out.println() statement.

Find the GCD of Two Numbers Using while Loop and if Statement 

Here is a program to find the GCD of two numbers to help you understand the use of the “while” loop:

public class GCDExample {
    public static void main(String[] args) {
        int number1 = 36;
        int number2 = 48;
        int gcd = 1;
        // Find the smaller number between number1 and number2
        int smallerNumber = (number1 < number2) ? number1 : number2;
        int i = 1;
        while (i <= smallerNumber) {
            // Check if both number1 and number2 are divisible by i
            if (number1 % i == 0 && number2 % i == 0) {
                gcd = i; // Update gcd
            }
            i++; // Increment i
        }
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
    }
}

In this example, we have numbers number1 and number2, which may be positive or negative. We want to find the GCD of these numbers.

First, we find the absolute values of number1 and number2 using the Math.abs() method, which returns the positive value of a number.

Then, we call the findGCD() method with the absolute values of the numbers. This method uses the Euclidean algorithm to find the GCD of two numbers recursively.

The findGCD() method takes two parameters, number1 and number2. If number2 is 0, we have found the GCD, so we return number1. Otherwise, we recursively call findGCD() with number2 and number1 % number2.

Finally, we print the GCD of the original numbers (taking into account their signs) using the System.out.println() statement.

Find the GCD of Both Positive and Negative Numbers

We can use the absolute values of the numbers to find the GCD of both positive and negative numbers. Here's an example:

public class GCDExample {
    public static void main(String[] args) {
        int number1 = -36;
        int number2 = 48;
        // Find the absolute values of the numbers
        int absNumber1 = Math.abs(number1);
        int absNumber2 = Math.abs(number2);
        int gcd = findGCD(absNumber1, absNumber2);
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
    }
    // Recursive method to find GCD using Euclidean algorithm
    public static int findGCD(int number1, int number2) {
        if (number2 == 0) {
            return number1;
        }
        return findGCD(number2, number1 % number2);
    }
}

Find the GCD of Two Numbers Using a User-Defined Method

Here is another example of GCD of two numbers using the user-defined method:

import java.util.Scanner;
public class GCDExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int number1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int number2 = scanner.nextInt();
        int gcd = findGCD(number1, number2);
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
        scanner.close();
    }
    // User-defined method to find GCD using Euclidean algorithm
    public static int findGCD(int number1, int number2) {
        if (number2 == 0) {
            return number1;
        }
        return findGCD(number2, number1 % number2);
    }
}

In this example, we use the Scanner class to accept input from the user. The user is prompted to enter the two numbers.

We then call the findGCD() method and pass the input numbers to it. This method uses the Euclidean algorithm to find the GCD of two numbers recursively.

The findGCD() method takes two parameters, number1 and number2. If number2 is 0, we have found the GCD, so we return number1. Otherwise, we recursively call findGCD() with number2 and number1 % number2.

Finally, we print the GCD of the entered numbers using the System.out.println() statement.

Find the GCD of Two Numbers Using the Euclidean Algorithm

Here is an example of the GCD of two numbers using the Euclidean algorithm:

public class GCDExample {
    public static void main(String[] args) {
        int number1 = 36;
        int number2 = 48;
        int gcd = findGCD(number1, number2);
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
    }
    // Method to find GCD using Euclidean algorithm
    public static int findGCD(int number1, int number2) {
        while (number2 != 0) {
            int temp = number2;
            number2 = number1 % number2;
            number1 = temp;
        }
        return number1;
    }
}

We use the Euclidean algorithm to find the GCD. The algorithm repeatedly divides the larger number by the smaller number and updates the values until the remainder becomes 0.

We use a while loop in the findGCD() method to perform the division and updates. We store the value of number2 in a temporary variable temp before updating it with the remainder of the division (number1 % number2). We update number1 with the value of temp. This process continues until number2 becomes 0.

Find the GCD of Two Numbers Using Recursion

Here is another example of GCD of two numbers using the recursion:

public class GCDExample {
    public static void main(String[] args) {
        int number1 = 36;
        int number2 = 48;
        int gcd = findGCD(number1, number2);
        System.out.println("The GCD of " + number1 + " and " + number2 + " is " + gcd);
    }
    // Recursive method to find GCD
    public static int findGCD(int number1, int number2) {
        if (number2 == 0) {
            return number1;
        }
        return findGCD(number2, number1 % number2);
    }
}

The findGCD() method takes two parameters, number1 and number2. If number2 is 0, we have found the GCD, so we return number1. Otherwise, we recursively call findGCD() with number2 and number1 % number2, representing the remainder when number1 is divided by number2.

The recursion continues until the base case is reached, where number2 becomes 0, and the GCD is returned.

Conclusion

The GCD is a powerful tool in many computational problems, and being able to calculate it accurately and efficiently is crucial. Whether you are working on algorithms, number theory, or cryptography, the knowledge you have gained in this tutorial will prove valuable.

Now that you have a solid understanding of the GCD, we encourage you to practice implementing it in Java and explore its applications in different programming scenarios. You can also find the GCD of two numbers in C or the GCD of two numbers in Python. By building upon this knowledge and exploring further, you can continue to expand your programming skills and problem-solving abilities.

FAQs

1. Is it possible to calculate LCM after calculating the GCD of two numbers in Java?

Yes, it is possible to calculate the GCD and LCM of two numbers in Java simultaneously in the same class. To calculate the LCM using the GCD in Java, you can utilize the following formula:

LCM = (x * y) / GCD [x and y being the two numbers whose GCD has been determined]

2. How to calculate the GCD of two numbers in Python?

Python allows calculating the GCD of two numbers using special math.gcd() function. The function returns the GCD of the given numbers.

3. What is the GCD Java library?

In Java, no specific "GCD Java library" is dedicated solely to calculating the Greatest Common Divisor (GCD) of two numbers. However, Java does provide a built-in mathematical class called java.lang.Math, which offers a method for computing the GCD.

The java.lang.Math class includes a static method named gcd(), which calculates the GCD of two integers. The method takes two int arguments and returns their GCD as a positive integer.

Leave a Reply

Your email address will not be published. Required fields are marked *