forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCDUsingEuclid.java
More file actions
38 lines (33 loc) · 791 Bytes
/
GCDUsingEuclid.java
File metadata and controls
38 lines (33 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.thealgorithms.maths;
/**
* Euclidean algorithm to compute the Greatest Common Divisor (GCD).
* Wikipedia: https://en.wikipedia.org/wiki/Euclidean_algorithm
*/
public final class GCDUsingEuclid {
private GCDUsingEuclid() {
// Utility class
}
/**
* Computes GCD of two integers using Euclidean algorithm.
*
* @param a first integer
* @param b second integer
* @return gcd(a, b)
*/
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
}