我正在尝试解决这个问题: problem
通过动态编程,我能够解决这个问题,这是到目前为止的代码:
import java.util.Scanner;
public class Dy
{
static long[] storage = new long[20];
public static void main(String[] args)
{
Scanner sx = new Scanner(System.in);
storage[0] = sx.nextInt();
storage[1] = sx.nextInt();
int x = sx.nextInt();
System.out.println(beast(x-1));
}
public static long beast(int n)
{
if(n==0)
return storage[n];
if(n==1)
return storage[n];
if(storage[n]!=0)
return storage[n];
storage[n] = (beast(n-1)*beast(n-1)) + beast(n-2);
return storage[n];
}
}
但是这里真正的麻烦是,如果n大约是20,即使long
数据类型也无法保存该值,所以选择显然是 BigInteger
,但作为一个学习者,我想知道如何在 Java 中将 BigInteger 与数组一起使用?任何帮助将不胜感激,谢谢!
最佳答案
您可以使用Map<Integer, BigInteger>
以及类似的东西,
static Map<Integer, BigInteger> storage = new HashMap<>();
public static void main(String[] args) {
Scanner sx = new Scanner(System.in);
// Add 0 and 1.
storage.put(0, BigInteger.valueOf(sx.nextInt()));
storage.put(1, BigInteger.valueOf(sx.nextInt()));
int x = sx.nextInt();
System.out.println(beast(x - 1));
}
public static BigInteger beast(int n) {
if (!storage.containsKey(n)) {
BigInteger t = beast(n - 1);
storage.put(n, t.multiply(t).add(beast(n - 2)));
}
return storage.get(n);
}
关于java - 如何使用 BigInt 计算修改后的斐波那契数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113772/