3

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.

William Seemann
  • 3,440
  • 10
  • 44
  • 78

2 Answers2

2

I don't know of any libraries but here is a method of finding primes that is recommended in this SO answer.

Community
  • 1
  • 1
eliot
  • 1,319
  • 1
  • 14
  • 33
  • 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