Question: works:meaning no precision error::Just array out of bounds

```
long a[] =new long[1000000];
int no=2,n;
long i;
a[no]=i+a[n];
if(a[no]>longChain)
{
    longChain = a[no];
    startNo = no;
}

```

and when I do

```
long a[] =new long[1000000];
long no=2,n;
long i,longChain=1,startNo;
a[no]=i+a[n];
if(a[no]>longChain)
{
    longChain = a[no];
    startNo = no;
}

```

then loss of precision

found:long

required: int

what is the problem?

My Code for above problem, its ProjectEuler Problem No. 14

```
class P14
{
    public static void main(String args[])
    {
        long a[] =new long[1000000];
        long no=2,n;
        long i,longChain=1,startNo;
        a[1]=1;
        while(no<1000000)
        {
            n=no;
            i=0;
            while(n>no-1)
            {
                if(n%2==0)
                    n=n/2;
                else
                    n=3*n+1;
                i++;
                //System.out.println(n);
            }
            a[no]=i+a[n];
            if (a[no] > longChain)
            {
                longChain=a[no];
                startNo=no;
            }
            no++;
            //System.out.println(no);
        }
    }
}

```

This is my code for where above problem is occurring

Answer:: Replace a[no] by a[(int)n]

a[n],a[(int)n]

Answer: 
The problem you have is that you cannot store all the possible values you are calculating in array. Numbers can grow beyond 2^31-1 and you get an overflow.

What you can do is make 

```
long n;

```

and

```
while (n > no - 1 || n >= a.length) {

}
// is safe as n < a.length;
a[no] = i + a[(int) n];

```

This ensures you only look up cached values which are inside your array.
`n` needs to be long because it may get too large for int. (If you use int it will overflow into negative numbers and cause the ArrayIndexOutOfBoundsException.)

You have to declare `n` as `long` and cast it to int when using it as index (`no` can be int)

```
a[no]=i+a[(int)n];

```