Skip to content

Commit 993f30b

Browse files
authored
Merge pull request TheAlgorithms#993 from shellhub/dev
update gcd
2 parents 7eea1d6 + 856dd06 commit 993f30b

File tree

2 files changed

+61
-10
lines changed

2 files changed

+61
-10
lines changed

Others/GCD.java renamed to Maths/GCD.java

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package Others;
1+
package Maths;
22

33
/**
44
* This is Euclid's algorithm which is used to find the greatest common denominator
@@ -8,21 +8,36 @@
88
*/
99
public class GCD {
1010

11+
/**
12+
* get greatest common divisor
13+
*
14+
* @param num1 the first number
15+
* @param num2 the second number
16+
* @return gcd
17+
*/
1118
public static int gcd(int num1, int num2) {
19+
if (num1 < 0 || num2 < 0) {
20+
throw new ArithmeticException();
21+
}
1222

13-
if (num1 == 0)
14-
return num2;
15-
16-
while (num2 != 0) {
17-
if (num1 > num2)
18-
num1 -= num2;
19-
else
20-
num2 -= num1;
23+
if (num1 == 0 || num2 == 0) {
24+
return Math.abs(num1 - num2);
2125
}
2226

23-
return num1;
27+
while (num1 % num2 != 0) {
28+
int remainder = num1 % num2;
29+
num1 = num2;
30+
num2 = remainder;
31+
}
32+
return num2;
2433
}
2534

35+
/**
36+
* get greatest common divisor in array
37+
*
38+
* @param number contains number
39+
* @return gcd
40+
*/
2641
public static int gcd(int[] number) {
2742
int result = number[0];
2843
for (int i = 1; i < number.length; i++)

Maths/GCDRecursion.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package Maths;
2+
3+
/**
4+
* @author https://github.com/shellhub/
5+
*/
6+
public class GCDRecursion {
7+
public static void main(String[] args) {
8+
System.out.println(gcd(20, 15)); /* output: 5 */
9+
System.out.println(gcd(10, 8)); /* output: 2 */
10+
System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */
11+
}
12+
13+
/**
14+
* get greatest common divisor
15+
*
16+
* @param a the first number
17+
* @param b the second number
18+
* @return gcd
19+
*/
20+
public static int gcd(int a, int b) {
21+
22+
if (a < 0 || b < 0) {
23+
throw new ArithmeticException();
24+
}
25+
26+
if (a == 0 || b == 0) {
27+
return Math.abs(a - b);
28+
}
29+
30+
if (a % b == 0) {
31+
return b;
32+
} else {
33+
return gcd(b, a % b);
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)