有谁知道一个基于 Java 的库,它可以用来提供一定长度(k)的所有素数。例如,如果 k = 2,库将提供:11、13、17.. 87。
问问题
2044 次
2 回答
1
我也不知道图书馆。但这里有一些我写的代码可以做到这一点。我认为它也可以用于其他需求:
package com.sandbox;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class SandboxTest {
@Test
public void whenGettingNextThenItIsNextPrime() {
Primes primes = new Primes();
assertEquals((Long) 2L, primes.next());
assertEquals((Long) 3L, primes.next());
assertEquals((Long) 5L, primes.next());
assertEquals((Long) 7L, primes.next());
assertEquals((Long) 11L, primes.next());
}
@Test
public void whenPassingIn2ThenIsPrime() {
assertTrue(new Primes().isPrime(2));
}
@Test
public void getAllPrimesOfLength2() { //this does what your question asks
Primes primes = new Primes();
while (true) {
Long prime = primes.next();
int length = String.valueOf(prime).length();
if (length > 2) {
return; //we found them all
} else if (length == 2) {
System.out.println(prime);
}
}
}
}
这是实现:
package com.sandbox;
import java.util.Iterator;
public class Primes implements Iterator<Long>{
private long currentPrime = 1;
public boolean hasNext() {
return true;
}
public Long next() {
currentPrime++;
while (!isPrime(currentPrime)) {
currentPrime++;
}
return currentPrime;
}
/**
* Optimize this on your own
*/
public boolean isPrime(long numberInQuestion) {
for (int i = 2; i < numberInQuestion - 1; i++) {
if (numberInQuestion % i == 0) {
return false;
}
}
return true;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
于 2013-03-26T01:03:51.520 回答