简体   繁体   English

使用筛子的质数高达 10^8

[英]Prime numbers upto 10^8 using sieve

Why this code is working only number less than 10^4?为什么此代码仅在小于 10^4 的数字上有效? i need to find all the prime numbers less than 10^8 but this is showing arrayindexoutofbound exception?我需要找到所有小于 10^8 的素数,但这显示 arrayindexoutofbound 异常? why?为什么? i know we can only create array till size10^8(correct me if i am wrong) but this is not even working for 10^5.我知道我们只能创建数组直到 size10^8(如果我错了,请纠正我)但这甚至不适用于 10^5。

 class Prime
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            boolean[] prime = new boolean[100000000];
            prime[2]=true;
            int i;
            for(i=3; i<100000000; i+=2)
                prime[i]=true;
            for(i=3; i<100000000; i++)  
            {
                if(prime[i]==true)
                    for(int j=i*i; j<100000000; j=j+i)
                        prime[j]=false;
            }
            for(i=1; i<100000000; i++)
            {
                if(prime[i]==true)
                System.out.println(i);
            }
        }
    }

The problem is here:问题在这里:

for(int j=i*i; j<100000000; j=j+i)

Since i can be as large as 99999999, i*i may be higher than Integer.MAX_VALUE , which will cause numeric overflow.由于i可以大到 99999999,所以i*i可能高于Integer.MAX_VALUE ,这会导致数值溢出。 As a result, j will be initialized to a negative value, and prime[j] will throw an exception.结果, j将被初始化为负值,而prime[j]将抛出异常。

To fix the problem, you can simply add a condition that requires the j must be positive:要解决此问题,您可以简单地添加一个要求j必须为正的条件:

for(int j=i*i; j > 0 && j<100000000; j=j+i)
for(int j=i*i; j<10000; j=j+i)

if i is 10^5, then the j would be 10^10, which would cause overflow for int type (max value of int type is 2^31 - 1 = 2147483647)如果 i 为 10^5,则 j 为 10^10,这将导致 int 类型溢出(int 类型的最大值为 2^31 - 1 = 2147483647)

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

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