Find GCD in Java
What you’ll learn
- Definition of
gcd(a,b)and special casegcd(0,n). - Iterative and recursive Euclidean algorithm in Java.
- Practical uses in fractions, modular arithmetic, and LCM.
Prerequisites
- Java basics: methods, loops, and
%remainder. - Use
Math.absto normalize signs before Euclid.
Reduction rule
gcd(a,b) = gcd(b, a % b) for b != 0, so each step reduces the problem size.
Intuition
gcd(48,18) -> gcd(18,12) -> gcd(12,6) -> gcd(6,0) = 6.
Live preview
Enter two integers and compute gcd using Euclid.
Algorithm
Goal: compute gcd(a,b) using Euclid's reduction.
Normalize signs
Use Math.abs so the final gcd is nonnegative.
Euclidean loop
While b != 0, set (a,b) = (b, a % b).
Return answer
When b == 0, return a.
📜 Pseudocode
function gcd(a, b):
a = abs(a)
b = abs(b)
while b != 0:
(a, b) = (b, a mod b)
return aIterative Euclidean algorithm
public class Main {
static int findGcd(int num1, int num2) {
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
public static void main(String[] args) {
int number1 = 48;
int number2 = 18;
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + findGcd(number1, number2));
}
}GCD of 48 and 18 is: 6
Recursive Euclidean algorithm
public class Main {
static int gcdRecursive(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
if (b == 0) return a;
return gcdRecursive(b, a % b);
}
public static void main(String[] args) {
int number1 = 48;
int number2 = 18;
System.out.println("GCD of " + number1 + " and " + number2 + " is: " + gcdRecursive(number1, number2));
}
}GCD of 48 and 18 is: 6
Applications
Fractions: reduce p/q by dividing numerator and denominator by gcd.
LCM: lcm(a,b) = |a*b| / gcd(a,b).
Also used in: modular inverse, Diophantine equations, and cryptography basics.
Optimization note
Euclid is already optimal for interview-sized int/long inputs.
For very large integers, use BigInteger.gcd.
❓ FAQ
🔄 Input / output examples
| (a,b) | gcd |
|---|---|
(48, 18) | 6 |
(17, 13) | 1 |
(0, 21) | 21 |
Edge cases
Convention
gcd(0,0) is convention-based; this page returns 0.
Negative values
Normalize signs before Euclid for predictable positive gcd.
Type width
For very large values, prefer long or BigInteger.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Iterative Euclid | O(log min(a,b)) | O(1) |
| Recursive Euclid | O(log min(a,b)) | O(log min(a,b)) stack |
Summary
- Use Euclid update
(a,b) = (b, a % b)untilb = 0. - Normalize signs and define behavior for
gcd(0,0).
Bezout identity: for integers a, b not both zero, there exist integers x, y with gcd(a,b) = a*x + b*y. Extended Euclid finds these coefficients.
8 people found this page helpful
