- Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathGcdAndGcm.java
More file actions
Latest commit
52 lines (42 loc) · 1.23 KB
/
Copy pathGcdAndGcm.java
File metadata and controls
52 lines (42 loc) · 1.23 KB
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
packagealgorithm.basicMath;
importorg.junit.Test;
importstaticorg.hamcrest.CoreMatchers.is;
importstaticorg.junit.Assert.assertThat;
publicclassGcdAndGcm {
/*
TASK
입력받은 두 수의 최대 공약수, 최소 공배수를 구한다.
*/
@Test
publicvoidtest() {
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));
}
publicintgcdByIteration(inta, intb) {
if (a < 0 || b < 0) return -1;
intmod;
while (b != 0) {
mod = a % b;
a = b;
b = mod;
}
returna;
}
publicintgcdByRecursion(inta, intb) {
if (a < 0 || b < 0) return -1;
if (b == 0) {
returna;
}
returngcdByRecursion(b, a % b);
}
publicintgcm(inta, intb) {
returna * b / gcdByRecursion(a, b);
}
}