- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathGCDRecursion.java
41 lines (36 loc) · 882 Bytes
/
GCDRecursion.java
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
39
40
41
packagecom.thealgorithms.maths;
/**
* @author https://github.com/shellhub/
*/
publicfinalclassGCDRecursion {
privateGCDRecursion() {
}
publicstaticvoidmain(String[] args) {
System.out.println(gcd(20, 15));
/* output: 5 */
System.out.println(gcd(10, 8));
/* output: 2 */
System.out.println(gcd(gcd(10, 5), gcd(5, 10)));
/* output: 5 */
}
/**
* get greatest common divisor
*
* @param a the first number
* @param b the second number
* @return gcd
*/
publicstaticintgcd(inta, intb) {
if (a < 0 || b < 0) {
thrownewArithmeticException();
}
if (a == 0 || b == 0) {
returnMath.abs(a - b);
}
if (a % b == 0) {
returnb;
} else {
returngcd(b, a % b);
}
}
}