java

Write a Program to Find the GCD of Two Numbers in Java

In this tutorial, we are going to see how to write a program that find the GCD of two numbers in Java. The GCD or the Greatest Common Divisor of two integers is the largest integer that can divide exactly two numbers (without remainder). Example:
 


 
 

Example: Find the GCD of Two Numbers Using for loop
public class Main {

    public static void main(String[] args) {

        int n1 = 60, n2 = 36, gcd = 0;

        for(int i=1; i <= n1 && i <= n2; i++)
        {
            if(n1% i==0 && n2%i==0)
                gcd = i;
        }
        System.out.printf("GCD of %d and %d is: %d", n1, n2, gcd);
    }
}

Output:

GCD of 60 and 36 is: 12

 

 

Example: Find the GCD of Two Numbers Using while loop
public class Main {

    public static void main(String[] args) {

        int n1 = 60, n2 = 36;

        while (n1 != n2) {
        	if(n1 > n2)
                n1 = n1 - n2;
            else
                n2 = n2 - n1;
        }

		System.out.printf("GCD = %d", n2);
    }
}

Output:

GCD = 12
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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