简体   繁体   English

prime1 spoj生成两个数字之间的质数

[英]prime1 spoj generating prime numbers between two number

package primesieve1;

import java.io.InputStreamReader;
import java.util.Scanner;

public class Primesieve1 {

    public boolean[] sieveOfEratosthenes(int max){

    boolean[] primeno; //defaults to false
        primeno = new boolean[max];
    for(int i=2; i<max; i++ ){primeno[i]=true;}

    for(int i=2; i<Math.sqrt(max);i++){
        if(primeno[i] == true){
            //all multiples of i*i, except i, are not primeno
            for(int j = i + i; j<max; j=j+i){
                primeno[j]=false;
            }
        }

    }
    return primeno;
}

    public void printTrue(boolean[] arr){
    for(int i=0; i<arr.length; i++){
        if(arr[i]==true){
            System.out.print(i + ", ");
        }
    }
    }

    public static void main(String[] args) {

        System.out.println("enter limit");
        Scanner sc = new Scanner(new InputStreamReader(System.in));
     int a = sc.nextInt();
        boolean a1[];
        Primesieve1 obj = new Primesieve1();
        a1 = obj.sieveOfEratosthenes(a);

        obj.printTrue(a1);

    }
}

giving out this error didnt understand why java.lang.OutOfMemoryError: Java heap space 给出此错误不理解为什么java.lang.OutOfMemoryError:Java堆空间

Although I'm not 100% sure I think a boolean[] still uses about 1 byte per entry. 尽管我不是100%肯定,但我认为boolean []仍会为每个条目使用大约1个字节。 Max will probably get quite big so even increasing the memory for the JVM will probably not do the trick. Max可能会变得很大,因此即使增加JVM的内存也可能无法解决问题。 One thing you can do however is not use a boolean[] but a BitSet instead, this way you'll only use 1 bit per number and thus you can probably cover until the max value of int. 但是,您可以做的一件事不是使用boolean []而是使用BitSet ,这样,每个数字将只使用1位,因此您可以覆盖直到int的最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM