实现另一个类来创建前100个素数

时间:2016-03-30 02:22:35

标签: java validation testing primes implementation

好吧,我有点担心我必须做的任务。我们必须从 wiley.com/go/javaexamples (第10章示例)中实现一个序列类来创建一个名为PrimeSequence的新类,它必须右对齐前100个素数序列号。我不明白实现其他类的意义,我做了但我知道我不遵循分配规则,因为我不明白我应该从其他类实现什么,我也不使用其他类。我不确定我该做什么

序列类

public interface Sequence 
{   
    int next();
}

PrimeSequence Class

public class PrimeSequence implements Sequence
{

public PrimeSequence()
{

}

public boolean isPrime(int x)
{
    for (int start = 2; start <= Math.sqrt(x); start++)
    {
        if (x % start == 0) 
        {
            return false;
        }
    }
    return true;
}

    public int next()
    {

    }
}

PrimeSequenceTester

public class PrimeSequenceTester {


public static void main(String[] args) 
{
    PrimeSequence prime = new PrimeSequence();

    int currentNumber = 2;
    int primesFound = 0;

    while (primesFound < 100) {
        if (prime.isPrime(currentNumber)) 
        {
            primesFound++;

            System.out.printf("%4s",currentNumber + " ");
            if (primesFound % 10 == 0) 
            {
                System.out.println();
            }
        }

        currentNumber++;
}
}

1 个答案:

答案 0 :(得分:0)

以下是使用Eratosthenes筛选(仅筛选奇数)并优化为仅在序列的多个实例上筛选一次数的实施例。你需要做一些 LOT 更简单的事情并且只是跟踪当前素数是什么并覆盖next()函数,这样当它被调用时你继续增加当前素数的值直到你的isPrime()函数返回true然后返回该值。

import java.util.BitSet;

public class PrimeSequence implements Sequence {
    private static final BitSet OddPrimeSieve = new BitSet( 8000 );
    private static int MaxSievedPrime = 2;

    static {
        OddPrimeSieve.set(0, OddPrimeSieve.size() - 1, true );
    }

    private static int PrimeToIndex( final int prime ){
        return (prime - 3) / 2;
    }

    private static int IndexToPrime( final int index ){
        return 2*index + 3;
    }

    private static synchronized void setMaxSievedPrime( final int max ){
        MaxSievedPrime = max;
        for ( int index = PrimeToIndex( MaxSievedPrime ) + MaxSievedPrime;
                index < OddPrimeSieve.length();
                index += MaxSievedPrime )
            OddPrimeSieve.set( index, false );
    }

    int currentPrime = 2;

    @Override
    public synchronized int next() {
        final int current = currentPrime;
        if ( current == 2 )
        {
            currentPrime++;
        }
        else
        {
            if ( currentPrime > MaxSievedPrime )
                setMaxSievedPrime( currentPrime );
            currentPrime = IndexToPrime( OddPrimeSieve.nextSetBit( PrimeToIndex( currentPrime ) + 1 ) );
        }
        return current;
    }

    public static void main( final String[] args ){
        PrimeSequence p = new PrimeSequence();
        for ( int i = 0; i < 100; i++ )
            System.out.println( p.next() );
    }
}