简体   繁体   English

使用筛查发现小于长数的质数

[英]finding prime numbers less than a LONG number using sieve

I have to find number of prime numbers less than or equal to a given number n . 我必须找到小于或等于给定数n的质数。 I am using Sieve of Eratosthenes for finding primes. 我正在使用Eratosthenes筛子查找素数。

This is the code I've written: 这是我编写的代码:

static int find_prime(int n) {
    boolean[] arr = new boolean[n+1];
    Arrays.fill(arr, true);

for(int i=2;i<=n;i++) {
    if(arr[i]==true) {
        for(int j=2*i; j<=n; j+=i)
            arr[j] = false;
    }
}
int count=0;
for(int i=2;i<=n;i++) {
    //System.out.print(arr[i]+" ");
    if (arr[i] == true)
        count++;
    }
    return count;
}

This code works well for integer values, but I have to implement it for long numbers. 该代码对于integer数值非常有效,但是我必须对long integer实现它。 And Java doesn't allow creating long size array so boolean[] arr = new boolean[n+1]; 而且Java不允许创建long数组,因此boolean[] arr = new boolean[n+1]; doesn't work. 不起作用。 Can someone suggest me a way to solve this? 有人可以建议我解决此问题的方法吗?

You wouldn't have enough memory to represent the entire sieve, because it is in exabytes. 您将没有足够的内存来表示整个筛子,因为它以EB为单位。 Even BitSet is not going to fit all the indexes that you need, because ultimately it uses an array of long s to store the bits. 甚至BitSet也无法满足您所需的所有索引,因为最终它使用 long数组来存储位。

You can find your answer with a mixed approach: 您可以通过多种方式找到答案:

  • Build and run a sieve up to Integer.MAX_VALUE 建立并运行直到Integer.MAX_VALUE的筛子
  • Harvest primes up to Integer.MAX_VALUE into an array of long s 将最多Integer.MAX_VALUE填入一个long数组
  • Observe that you can stop checking for divisors upon reaching square root of candidate number c 观察到达到候选数c平方根后就可以停止检查除数
  • This means that you already have all potential divisors for values above Integer.MAX_VALUE 这意味着您已经具有大于Integer.MAX_VALUE所有潜在除数
  • Use array of divisors to filter numbers between Integer.MAX_VALUE and n 使用除数数组过滤Integer.MAX_VALUEn之间的数字

Since you do not need to store additional primes after Integer.MAX_VALUE , your code would not run out of memory. 由于您不需要在Integer.MAX_VALUE之后存储其他素数,因此您的代码不会耗尽内存。

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

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