Greatest Common Divisor in Java: Explanation & Practice
Find GCD of two numbers
Problem summary
Write a program that finds the Greatest Common Divisor (GCD) of two numbers using Euclidean algorithm.
Starter code
public class Main {
public static void main(String[] args) {
int a = 48;
int b = 18; // Test case 1
// Find GCD using Euclidean algorithm
// Print: GCD: <result>
}
}Expected output and test cases
- GCD(48, 18) = 6
GCD: 6
- GCD(25, 15) = 5
GCD: 5
- GCD(17, 13) = 1
GCD: 1
Hints
- Euclidean: GCD(a,b) = GCD(b, a%b)
- Continue until b becomes 0
- When b is 0, a is the GCD
Related Core Java Basics exercises
- Practice Calculate Factorial in Java
- Practice Palindrome Number Check in Java
- Practice Least Common Multiple in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler