Skip to content

Commit b3fda35

Browse files
committed
first n primes
1 parent a38cba9 commit b3fda35

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package joshua.algorithm.math;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* 输出前 N 个 质数,质数除1外只能被自身整除。
8+
*
9+
*
10+
* Created by joshu on 2016/5/25.
11+
*/
12+
public abstract class FirstNPrime {
13+
14+
public abstract List<Long> getFirstNPrime(int n);
15+
16+
/**
17+
* 类似 {@link joshua.leetcode.math.CountPrime} 的 方法。
18+
* 对每个数m,已知 小于m的所有的质数[2,..k,..],则对于小于m的开方的所有质数,如果都不能整除m,则m也是素数
19+
* 否则继续对m+1判断。
20+
*/
21+
public static class Solution1 extends FirstNPrime {
22+
23+
@Override
24+
public List<Long> getFirstNPrime(int n) {
25+
List<Long> primes = new ArrayList<Long>();
26+
primes.add(2L);
27+
int count = 1;
28+
long currentNum = 3;
29+
while (count < n) {
30+
int k = 0;
31+
// get the next prime, count == primes.size()
32+
while (k < count && primes.get(k) * primes.get(k) <= currentNum) {
33+
if (currentNum % primes.get(k) == 0) {
34+
k = 0;
35+
currentNum +=1;
36+
} else {
37+
k++;
38+
}
39+
}
40+
primes.add(currentNum);
41+
currentNum += 1;
42+
count++;
43+
}
44+
return primes;
45+
}
46+
}
47+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package joshua.algorithm.math;
2+
3+
import com.google.common.collect.Lists;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
/**
9+
* Created by joshu on 2016/5/25.
10+
*/
11+
public class FirstNPrimeTest {
12+
13+
@Test
14+
public void testSolution1() {
15+
FirstNPrime solution = new FirstNPrime.Solution1();
16+
assertEquals(Lists.newArrayList(2L,3L,5L,7L,11L), solution.getFirstNPrime(5));
17+
}
18+
}

0 commit comments

Comments
 (0)