基于Java的库,用于提供特定长度的质数。

3

有没有人知道一款基于Java的库,可以提供特定长度(k)的所有质数。例如,如果k=2,则该库将提供:11、13、17... 87。


你列出的所有数字需要超过2个比特才能指定。 - Hunter McMillen
@Hunter,不确定你的意思。你能澄清一下吗? - William Seemann
1
十进制数11在二进制中表示为1011。它需要4位来显示其二进制表示。 - Hunter McMillen
你是指k位数长度吗? - eliot
是的,这里不是指二进制,k位只是指数字的长度。编辑了问题以避免进一步的误解。 - William Seemann
2个回答

2

我不知道有任何相关的库,但这里提供了一种找到质数的方法,它被推荐在这个Stack Overflow答案中。


谢谢Eliot,虽然这不是“完美”的解决方案,但如果需要,我可以进行修改。我会再等一段时间,以便其他人可以提供答案。 - William Seemann

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接