[英]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: 您可以通过多种方式找到答案:
Integer.MAX_VALUE
Integer.MAX_VALUE
的筛子 Integer.MAX_VALUE
into an array of long
s Integer.MAX_VALUE
填入一个long
数组 c
c
平方根后就可以停止检查除数 Integer.MAX_VALUE
Integer.MAX_VALUE
所有潜在除数 Integer.MAX_VALUE
and n
Integer.MAX_VALUE
和n
之间的数字 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.