Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c0271a0

Browse files
committed
Add basic algorithm code about gcd
1 parent 3f2dc9c commit c0271a0

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package algorithm.basic;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
public class GcdAndGcm {
9+
10+
/*
11+
TASK
12+
입력받은 두 수의 최대 공약수를 구한다.
13+
*/
14+
15+
@Test
16+
public void test() {
17+
assertThat(gcdByIteration(-1, 0), is(-1));
18+
assertThat(gcdByIteration(0, 0), is(0));
19+
assertThat(gcdByIteration(6, 8), is(2));
20+
assertThat(gcdByIteration(3, 3), is(3));
21+
22+
assertThat(gcdByRecursion(-1, 0), is(-1));
23+
assertThat(gcdByRecursion(0, 0), is(0));
24+
assertThat(gcdByRecursion(6, 8), is(2));
25+
assertThat(gcdByRecursion(3, 3), is(3));
26+
27+
assertThat(gcm(6, 8), is(24));
28+
}
29+
30+
public int gcdByIteration(int a, int b) {
31+
if (a < 0 || b < 0) return -1;
32+
int mod;
33+
while (b != 0) {
34+
mod = a % b;
35+
a = b;
36+
b = mod;
37+
}
38+
return a;
39+
}
40+
41+
public int gcdByRecursion(int a, int b) {
42+
if (a < 0 || b < 0) return -1;
43+
if (b == 0) {
44+
return a;
45+
}
46+
return gcdByRecursion(b, a % b);
47+
}
48+
49+
public int gcm(int a, int b) {
50+
return a * b / gcdByRecursion(a, b);
51+
}
52+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package exercise;
2+
3+
/**
4+
* Created by Jbee on 2017. 6. 5..
5+
*/
6+
public class KnapsackProblem {
7+
}

0 commit comments

Comments
 (0)