簡體   English   中英

提高Java中Eratosthenes代碼的Sieve效率

[英]Improving efficiency of Sieve of Eratosthenes code in java

我曾在Java 中使用過Eratosthenes篩選器的代碼,但是我面臨一些時間和空間效率問題。 這是代碼:

import java.util.*;

class EratosthenesSeive
{

    public static void main(String args[])
    {

        ArrayList<Long> myPrimeList = new ArrayList<Long>();
        ArrayList<Long> myTempPrimeList = new ArrayList<Long>();
        ArrayList<Boolean> isPrimeNumber = new ArrayList<Boolean>();
        int index = 0;

        long ul = 1500l;
        long ll = 2;

        do
        {
            myTempPrimeList.add(ll);
            isPrimeNumber.add(true);
            ll++;
        }while( ll != (ul+1));

        for(long i : myTempPrimeList)
        {
            if(isPrimeNumber.get(index))
            {
                myPrimeList.add(i);
                for(long j = i ; j*i <= ul; j++)
                {
                    isPrimeNumber.set(myTempPrimeList.indexOf(j*i),false);
                }
            }
            index++;
        }

        System.out.println(myPrimeList);
    }
}

對於高達10 ^ 3的輸入似乎工作正常,在10 ^ 4時它只是掛起而在10 ^ 5及以上我得到OutOfMemoryError 而且代碼似乎工作正常,但我想把它加緊一點。 有什么建議么?

您裝箱/拆箱的代碼 您可能想嘗試使用基本類型的直數組替換ArrayList<>

通過不使用偶數來加倍速度。

一個可能的優化是使用基本類型數組替換ArrayLists,前提是您事先知道所需數組的大小。 這樣可以防止代碼中當前存在的所有值的不必要的裝箱/取消裝箱。

此外,請注意,您不必在數組中存儲偶數,只需要奇數 - 這樣做會將內存需求處理時間減少一半。

為了解決OutOfMemoryError,您可以在啟動時調整JVM的配置參數,從而為應用程序提供更多的堆空間。

您的代碼正在完成比它需要的工作更多的工作。 你只需要一個布爾數組,兩個循環來標記非素數,另一個循環來打印素數的索引號。 像這樣:

public void printPrimes(int max) {

    // declare a single array of booleans
    boolean[] primeFlags = new boolean[max + 1];

    // double loop sieve-style and mark non-primes as true
    for (int m = 2; m <= (int)Math.sqrt(max); m++) 
        for (int k = m*m; k <= max; k += m) primeFlags[k] = true;

    // loop over bool array and print indexes with false values 
    // which will be the prime numbers
    for (int m = 2; m <= max; m++)
        if (!primeFlags[m]) System.out.print(m + " ");
}
import java.util.Scanner;

//Sieve Of Erastothenes

public class SieveOfErastothenes {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a range n : ");
        int n = sc.nextInt();

        boolean ar[] = new boolean[n+1];
        for (int i=2;i<=n;i++)
        ar[i] = true;

        for(int i = 2;i*i<=n;i++)
        {
            if(ar[i])
            {
                for(int j=i;i*j<=n;j++)
                    ar[i*j]=false;
            }
        }

        for(int i=2;i<=n;i++)
        {
            if(ar[i])
                System.out.print(i+" ");
        }
        sc.close();

    }

}

/*This code is contributed by Asish Samantaray*/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM