JavaAlgorithms/Maths/GCDRecursion.java

35 lines
709 B
Java
Raw Permalink Normal View History

2019-10-08 12:37:17 +08:00
package Maths;
2020-10-24 18:23:28 +08:00
/** @author https://github.com/shellhub/ */
2019-10-08 12:37:17 +08:00
public class GCDRecursion {
2020-10-24 18:23:28 +08:00
public static void main(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 */
}
2019-10-08 12:37:17 +08:00
2020-10-24 18:23:28 +08:00
/**
* get greatest common divisor
*
* @param a the first number
* @param b the second number
* @return gcd
*/
public static int gcd(int a, int b) {
2019-10-08 12:37:17 +08:00
2020-10-24 18:23:28 +08:00
if (a < 0 || b < 0) {
throw new ArithmeticException();
}
2019-10-08 12:37:17 +08:00
2020-10-24 18:23:28 +08:00
if (a == 0 || b == 0) {
return Math.abs(a - b);
}
2019-10-08 12:37:17 +08:00
2020-10-24 18:23:28 +08:00
if (a % b == 0) {
return b;
} else {
return gcd(b, a % b);
2019-10-08 12:37:17 +08:00
}
2020-10-24 18:23:28 +08:00
}
2019-10-08 12:37:17 +08:00
}