On this tutorial page we are going to learn how to write a Java program to find GCD of Two numbers.
The Greatest Common Divisor (GCD) of two numbers is the largest positive integer that divides both numbers without leaving a remainder. There are different methods to find the GCD of two numbers, but the most common method is the Euclidean algorithm. Here are the steps to find the GCD of two numbers using the Euclidean algorithm:
Step 1: Let a and b be the two numbers for which we want to find the GCD.
Step 2: Divide the larger number by the smaller number, and write down the quotient and the remainder.
Step 3: If the remainder is 0, the GCD is the smaller number. If the remainder is not 0, replace the larger number with the smaller number, and replace the smaller number with the remainder. Repeat step 2 and 3 until the remainder is 0.
Step 4: The GCD is the last non-zero remainder obtained in step 3.
Following are examples of how to find the GCD (Greatest Common Divisor).
Example 1: Find GCD of Two Numbers using For Loop
Output
Enter the First Number: 240
Enter the Second Number: 150
GCD of 240 and 150 = 30
Example 2: Find GCD of Two Numbers using While Loop
Output
Enter the First Number: 102
Enter the Second Number: 85
GCD = 17
Example 3: Find GCD of Two Numbers without temp Variable
Output
Enter the First Number: 175
Enter the Second Number: 60
GCD = 5
Example 4: Find GCD of Two Numbers using Recursive Method
Output
Enter the First Number: 70
Enter the Second Number: 120
GCD of 70 and 120 = 10
That's all guys, hope this Java Program is helpful for you.
Happy Learning... 😀
Please share this article on social media to help others.
If you have any query or suggestion regarding this artical please share with us feedback@javabytechie.com