Skip to content

Commit 4832c6f

Browse files
add gcd
1 parent b47bc75 commit 4832c6f

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.examplehub.maths;
2+
3+
/**
4+
* https://en.wikipedia.org/wiki/Greatest_common_divisor
5+
*/
6+
public class GreatestCommonDivisor {
7+
8+
/**
9+
* Returns the greatest common divisor of two numbers.
10+
*
11+
* @param a the first number the.
12+
* @param b the second number.
13+
* @return the greatest common divisor of two numbers.
14+
*/
15+
public static int gcdEasy(int a, int b) {
16+
if (a == 0 || b == 0) {
17+
return Math.max(a, b);
18+
}
19+
for (int i = Math.min(a, b); i >= 1; i--) {
20+
if (a % i == 0 && b % i == 0) {
21+
return i;
22+
}
23+
}
24+
return -1; /* not found */
25+
}
26+
27+
/**
28+
* Returns the greatest common divisor of two numbers.
29+
*
30+
* @param a the first number the.
31+
* @param b the second number.
32+
* @return the greatest common divisor of two numbers.
33+
*/
34+
public static int gcd(int a, int b) {
35+
return b == 0 ? a : gcd(b, a % b);
36+
}
37+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.examplehub.maths;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class GreatestCommonDivisorTest {
8+
@Test
9+
void testGCD() {
10+
int[][] testNumbers = {{8, 12, 4}, {54, 24, 6}, {3, 4, 1}, {3, 0, 3}};
11+
for (int[] testNumber : testNumbers) {
12+
assertEquals(testNumber[2], GreatestCommonDivisor.gcdEasy(testNumber[0], testNumber[1]));
13+
assertEquals(testNumber[2], GreatestCommonDivisor.gcd(testNumber[0], testNumber[1]));
14+
}
15+
}
16+
}

0 commit comments

Comments
 (0)