Eratosthenes筛(最小和最大)

时间:2018-01-16 16:36:02

标签: java primes sieve-of-eratosthenes

我使用Sieve of Eratosthenes算法查找范围内的素数(从最小值到最大值)。但是,如果我包含最小值,我似乎无法使它工作。

这是我在Java中的代码:

  protected static List<Integer> getSievePrimes(int a, int b) {
    List<Integer> primeNumbers = new ArrayList();

    boolean [] isComposite = new boolean [b + 1];
    isComposite[1] = true;

    // Mark all composite numbers
    for (int i = 2; i <= b; i++) {
//    for (int i = a == 1 ? 2 : a; i <= b; i++) {
        if (!isComposite[i]) {
            // 'i' is a prime number
            //if (i >= a) {
                primeNumbers.add(i);
            //}
            int multiple = 2;
            while (i * multiple <= b) {
                isComposite [i * multiple] = true;
                multiple++;
            }
        }
    }

    return primeNumbers;
  }

正如您所看到的,它目前仅满足最大值(b),而不是最小值(a)。

问题

如何修改上述方法以满足最小和最大?

1 个答案:

答案 0 :(得分:0)

public boolean isPrime( int test ) 
{

  int k;

  if( test < 2 )
    return false;
  else if( test == 2 )  
    return true;
  else if( ( test > 2 ) && ( test % 2 == 0 ) )
    return false;
  else
  {
    for( k = 3; k < ( test/2 ); k += 2 )
    {
        if( test % k == 0 ) 
            return false;
    }
  }

  return true;
}

public void sieveOfEratosthenes( int first, int last )
{
  boolean[ ] sieve = new boolean[ ( last - first ) + 1 ];

  int count = 0;
  int index = 0;

  int cursor = first;
  int end = last;

  while( cursor <= end )
  {
     if( isPrime( cursor ) != sieve[ index ] )
     {
        System.out.println( cursor+" " );
        count++;
     }

     cursor++;
     index++;
  }

  cursor = first;

  if( count == 0 )
     System.out.println( "There are "+count+" primes from "+cursor+" to "+end+"." );
  else if( count == 1 )
     System.out.println( "is the "+count+" prime from "+cursor+" to "+end+"." );
  else
     System.out.println( "are the "+count+" primes from "+cursor+" to "+end+"." );
}