【发布时间】:2015-08-11 01:08:36
【问题描述】:
我正在开发一个程序,该程序应该返回给定数字沿斐波那契数列的位置。
很简单,但 Codeabbey 上的测试用例长度超过 100 位。这超出了 long 原始数据类型可以处理的范围。我知道我需要使用 BigInteger,但我不确定如何在我的代码中实现它。我读到 BigInteger 是不可变的?这是什么意思?
这是我的代码:
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] + " ");
}
}
编辑: 这是我使用 BigInteger 更新的代码。仍然没有运气。
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] + " ");
}
}
编辑:想通了。感谢所有的帮助!
【问题讨论】:
标签: java biginteger fibonacci