特定の長さ(k)のすべての素数を提供するために使用できるJavaベースのライブラリを知っている人はいますか。たとえば、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 に答える