MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / gcd

Method gcd

src/main/java/com/thealgorithms/maths/GCD.java:34–49  ·  view source on GitHub ↗

get the greatest common divisor @param num1 the first number @param num2 the second number @return gcd

(int num1, int num2)

Source from the content-addressed store, hash-verified

32 * @return gcd
33 */
34 public static int gcd(int num1, int num2) {
35 if (num1 < 0 || num2 < 0) {
36 throw new ArithmeticException();
37 }
38
39 if (num1 == 0 || num2 == 0) {
40 return Math.abs(num1 - num2);
41 }
42
43 while (num1 % num2 != 0) {
44 int remainder = num1 % num2;
45 num1 = num2;
46 num2 = remainder;
47 }
48 return num2;
49 }
50
51 /**
52 * @brief computes gcd of an array of numbers

Calls 1

absMethod · 0.45