-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathGcdAndGcm.java
52 lines (42 loc) · 1.23 KB
/
GcdAndGcm.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
42
43
44
45
46
47
48
49
50
51
52
package algorithm.basicMath;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class GcdAndGcm {
/*
TASK
입력받은 두 수의 최대 공약수, 최소 공배수를 구한다.
*/
@Test
public void test() {
assertThat(gcdByIteration(-1, 0), is(-1));
assertThat(gcdByIteration(0, 0), is(0));
assertThat(gcdByIteration(6, 8), is(2));
assertThat(gcdByIteration(3, 3), is(3));
assertThat(gcdByRecursion(-1, 0), is(-1));
assertThat(gcdByRecursion(0, 0), is(0));
assertThat(gcdByRecursion(6, 8), is(2));
assertThat(gcdByRecursion(3, 3), is(3));
assertThat(gcm(6, 8), is(24));
}
public int gcdByIteration(int a, int b) {
if (a < 0 || b < 0) return -1;
int mod;
while (b != 0) {
mod = a % b;
a = b;
b = mod;
}
return a;
}
public int gcdByRecursion(int a, int b) {
if (a < 0 || b < 0) return -1;
if (b == 0) {
return a;
}
return gcdByRecursion(b, a % b);
}
public int gcm(int a, int b) {
return a * b / gcdByRecursion(a, b);
}
}