【问题标题】:Using Sieve of Erastothene to find primes 2 to 1000 [duplicate]使用 Erastothene 筛法找到 2 到 1000 的素数 [重复]
【发布时间】:2014-11-14 20:22:27
【问题描述】:

我一直在尝试寻找有关如何使用 Erastothenes 筛子使用数组打印从 2 到 1000 的素数的帮助。我查看了 Sieve 的工作原理,但无法弄清楚如何对其进行编码。

import java.util.*;
public class PrimeArray {

public static boolean isPrime(int n){
    if(n<=1){
        return false;
    }
    for(int i = 2; i*i<n; i++){
        if(i%n==0)
            return false;
    }
    return true;
}

public static void main(String[] args) {
    int[] array = new int[1000];
        for(int j = 2; j<array.length; j++){
            if(isPrime(j))
                System.out.println(array[j]);

            }

        }



    }

【问题讨论】:

标签: java arrays primes


【解决方案1】:

您的isPrime() 函数使用了试用版,并且有两个错误。一,测试n % i == 0不是i % n == 0和两个(i * i) &lt;= n(不是(i * i) &lt; n)。如果我使用它可以正常工作,

public static boolean isPrime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; (i * i) <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Java 数组不是动态数据结构。要使用上述方法将 2 到 1000 以下的最后一个素数放入数组中,您可以这样做

public static void main(String[] args) {
    int[] array = new int[168]; // the 168th prime is 997
    int pos = 0;
    for (int j = 2; pos < array.length; j++) {
        if (isPrime(j)) {
            array[pos++] = j;
        }
    }
    System.out.println(Arrays.toString(array));
}

【讨论】:

    【解决方案2】:

    这里是埃拉托色尼筛法的快速版本:

    public BitSet sieve(long max){
        if(max < 3) return;
    
        BitSet isPrime = new Bitset((int)(max + 1 / 2))
        ArrayList<Long> primes = new ArrayList<long>();
    
        primes.add(2)
        isPrime.set(0, true)
    
        max = (long) Math.sqrt(max);
    
        for(int i = 3; i < max; i+= 2){
            boolean a = true;
    
            for(int j = 0; j < primes.size(); j++){
                if(i % primes.get(j) == 0){
                    a = false;
                    break;
                }
            }
    
            if(a){
                primes.add(i);
                isPrimes.set((i - 1) / 2, true);
            }
    
        }
    
        return isPrime;
    }
    

    【讨论】:

    • 这不是埃拉托色尼的筛子,它使用试除法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2016-11-18
    相关资源
    最近更新 更多