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: 
your no and n variables need to be int, not long. Arrays can't be indexed by long. Changing the code to:

```
int no=2,n;

```

makes the code compile.

The ArrayIndexOutOfBoundsException is because you wrote the algorithm assuming it was longs.

This code will eventually cause `n` to become negative:

```
n=3*n+1;

```

It's hard to see why when you're doing integer arithmetic. A slight change to make the code use long arithmetic and print the interim result reveals exactly when it becomes negative and how:

```
while(n>no-1)
{
    long newN = n;

    if (n % 2 == 0) newN = newN / 2L;
    else newN = 3L * newN + 1L;

    if (newN > Integer.MAX_VALUE) System.out.println("about to fail");

    //this is where the magic happens
    n = (int)newN;
    System.out.println("converted " + newN + " to " + n);

    i++;
}

```
This is likely because array indexing takes an `int` as the index. But all your variables are of type `long`.

```
a[no]

```

`no` is a `long`.

So using `long` as an array index is an implicit downcast which could result in loss of precision.

So either you manually cast it down, or you change `no` to an `int`.

**EDIT: (after additional info in the question)**

I'm not 100% sure if this is the cause:

```
n=3*n+1;

```

You use `n` as in index. But `n` can get pretty large to begin with. So a `*3` could make it larger than the size of the array.

You should probably double-check whatever your algorithm is. (which I can't figure out from the code itself)