0

for the Given below code after int Input Value of 46348 i am getting ArrayIndexOutOfBoundsException. I am given Condition in for loop that keeps the array limits. But somehow i am getting this exception and i unable to figure it out. And my requirement is find all primenumbers below given number.

 Scanner sc = new Scanner(System.in);
    int n= sc.nextInt();
    int[] arr= new int[n+1];
            for(int i=2;i<=n;i++)
            {
                if(arr[i]==0)
                {
                    for(j=i;j*i<=n;j++)
                        arr[j*i]=1; // Here i am getting Exception
                }
            }

Input:

46349

Output:

java.lang.ArrayIndexOutOfBoundsException: -2146737495

502802

Thanks.,

2 Answers 2

3

You have encountered an arithmetic overflow.

In Java, int data type is a 32-bit signed integer, which means it can have values between -2147483648 and 2147483647.

On this line:

for(j=i;j*i<=n;j++)

If i is 46349 then j becomes 46349, too. If you multiply 46349 by 46349, you get 2148229801, which is greater than 2147483647, so the integer overflows and becomes -2146737495. Naturally, it is less than 46349, so the check in the for-loop passes. But you cannot index an array with a negative value in Java, that's why you get the ArrayIndexOutOfBoundsException.

Range check your input value for n < 46340, or if it really needs to work with n = 46349 input, switch to long data type, which will work up to n = 3037000499.

Sign up to request clarification or add additional context in comments.

Comments

0

46349 * 46349 is too big to use as the index of a Java Array. The index is just a 32-bit signed integer, so has a maximum value of 2,147,483,648.

It passes the < n check because it overflows and comes back negative, so it is in fact less than n, but a negative number is not a legal array index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.