Skip to content

Commit 6f61e27

Browse files
authored
Add GCDUsingEuclid class to compute GCD
Implemented the Euclidean algorithm for GCD calculation.
1 parent e945f16 commit 6f61e27

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* Euclidean algorithm to compute the Greatest Common Divisor (GCD).
5+
* Wikipedia: https://en.wikipedia.org/wiki/Euclidean_algorithm
6+
*/
7+
public final class GCDUsingEuclid {
8+
9+
private GCDUsingEuclid() {
10+
// Utility class
11+
}
12+
13+
/**
14+
* Computes GCD of two integers using Euclidean algorithm.
15+
*
16+
* @param a first integer
17+
* @param b second integer
18+
* @return gcd(a, b)
19+
*/
20+
public static int gcd(int a, int b) {
21+
a = Math.abs(a);
22+
b = Math.abs(b);
23+
24+
if (a == 0) {
25+
return b;
26+
}
27+
if (b == 0) {
28+
return a;
29+
}
30+
31+
while (b != 0) {
32+
int remainder = a % b;
33+
a = b;
34+
b = remainder;
35+
}
36+
return a;
37+
}
38+
}

0 commit comments

Comments
 (0)