File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments