2013-03-26 62 views
3

有誰知道可用於提供特定長度(k)的所有素數的基於Java的庫。例如,如果k = 2,庫將提供:11,13,17 .. 87.基於Java的庫提供特定長度的素數

+0

時間超過2位,指定所有你列出的電話號碼。 – 2013-03-26 00:42:38

+0

@Hunter,不知道你的意思。你能澄清嗎? – 2013-03-26 00:47:08

+1

基數爲10的數字11是二進制的「1011」。它需要4位來顯示它的二進制表示 – 2013-03-26 00:49:02

回答

2

我不知道任何庫,但here是找到在this SO回答中推薦的質數的方法。

+0

感謝eliot,而不是「完美」的解決方案,但我可以在必要時進行修改。我會稍後再打開這個問題,以便其他人可以提供一個答案,如果他們有一個。 – 2013-03-26 00:55:45

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(); 
    } 
}