forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGcd.java
More file actions
34 lines (30 loc) · 923 Bytes
/
Gcd.java
File metadata and controls
34 lines (30 loc) · 923 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
/**
* Computes the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm.
*
* <p>Time: ~O(log(a + b))
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.math;
public class Gcd {
/**
* Computes the Greatest Common Divisor (GCD) of a and b. The returned value is always
* non-negative.
*/
public static long gcd(long a, long b) {
if (b == 0)
return Math.abs(a);
return gcd(b, a % b);
}
public static void main(String[] args) {
System.out.println(gcd(12, 18)); // 6
System.out.println(gcd(-12, 18)); // 6
System.out.println(gcd(12, -18)); // 6
System.out.println(gcd(-12, -18)); // 6
System.out.println(gcd(5, 0)); // 5
System.out.println(gcd(0, 5)); // 5
System.out.println(gcd(-5, 0)); // 5
System.out.println(gcd(0, -5)); // 5
System.out.println(gcd(0, 0)); // 0
}
}