Does anyone know of a Java-based library that can be used to provide all prime numbers of a certain length (k). For instance, if k = 2 the library would provide: 11, 13, 17.. 87.
Asked
Active
Viewed 2,693 times
3
-
it takes more than 2 bits to specify all of the numbers you listed. – Hunter McMillen Mar 26 '13 at 00:42
-
@Hunter, not sure what you mean. Can you clarify? – William Seemann Mar 26 '13 at 00:47
-
1The base 10 number 11 is `1011` in binary. It takes `4` bits to show its binary representation – Hunter McMillen Mar 26 '13 at 00:49
-
Do you mean k-digit length? – eliot Mar 26 '13 at 00:49
-
Yep, not referring to binary, k-bit just means the length of the number. Edited the question to avoid further misinterpretation. – William Seemann Mar 26 '13 at 00:50
2 Answers
2
-
Thanks eliot, not the "perfect" solution but I can modify this if necessary. I will leave this question open a little while longer so others can offer an answer if they have one. – William Seemann Mar 26 '13 at 00:55
1
I also don't know of a library. But here is some code I wrote that can do this. I think it's pretty reusable for other needs too:
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);
}
}
}
}
And here's the implementation:
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();
}
}

Daniel Kaplan
- 62,768
- 50
- 234
- 356