I am working on a program that is supposed to return the position of a given number along the Fibonacci Sequence.
Simple enough, but the test-cases on Codeabbey are over 100 digits long. This is more than the long primitive data type can handle. I know I need to use BigInteger, but I am not sure how to implement it into my code. I read that BigInteger is immutable? What does this mean?
Here is my code:
import java.util.Scanner;
class codeabbey67
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
System.out.print("Sets: ");
int sets = input.nextInt();
long A[] = new long[sets];
for(int i = 0; i<sets; i++)
{
long f = 0;
long s = 1;
long next = 0;
long j = 0;
System.out.print("\nVal: ");
long val = input.nextLong();
while(next != val)
{
if(j<= 1)
{
next = 1;
j++;
}
next = f+s;
f = s;
s = next;
j++;
}
A[i] = j;
}
System.out.println("\nRESULTS: ");
for(int j = 0; j<A.length; j++)
System.out.print(A[j] + " ");
}
}
EDIT: Here is my updated code with BigInteger. Still no luck.
import java.util.Scanner;
import java.math.BigInteger;
class codeabbey67
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
System.out.print("\n\nSets: ");
int sets = input.nextInt();
int A[] = new int[sets];
for(int i = 0; i<sets; i++)
{
BigInteger f = BigInteger.ZERO;
BigInteger s = BigInteger.ONE;
BigInteger next = BigInteger.ZERO;
BigInteger j = BigInteger.ZERO;
System.out.print("\nVAL: ");
BigInteger val = input.nextBigInteger();
int x = 0;
while(!next.equals(val) && x!= 1000) //until current value at position in sequence equals desired value
{
if(x<= 1)
{
next = BigInteger.ONE;
x++;
}
next = f.add(s);
s=next;
x++;
}
A[i] = x;
}
for(int y = 0; y<A.length; y++)
System.out.print(A[y] + " ");
}
}
EDIT: Figured it out. Thanks for all of the help!