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]
your no and n variables need to be int, not long. Arrays can’t be indexed by long. Changing the code to:
makes the code compile.
The ArrayIndexOutOfBoundsException is because you wrote the algorithm assuming it was longs.
This code will eventually cause
nto become negative: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: