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.,
You have encountered an arithmetic overflow.
In Java,
intdata type is a 32-bit signed integer, which means it can have values between -2147483648 and 2147483647.On this line:
If
iis 46349 thenjbecomes 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 thefor-loop passes. But you cannot index an array with a negative value in Java, that’s why you get theArrayIndexOutOfBoundsException.Range check your input value for
n < 46340, or if it really needs to work withn = 46349input, switch tolongdata type, which will work up ton = 3037000499.