【发布时间】:2019-06-26 01:54:10
【问题描述】:
我正在尝试使用 java 解决斐波那契,但我的代码需要很长时间才能处理大数字。
问题描述
任务。给定一个整数 ????,找出 ????th 斐波那契数 ???????? 的最后一位(即 ???????? mod 10)。
输入格式。输入由一个整数组成 ????.
约束。 0 ≤ ???? ≤ 10⁷.
输出格式。输出????????的最后一位。
我的代码:
public class FibonacciLastDigit {
private static int getFibonacciLastDigitNaive(int n) {
if (n <= 1) {
return n;
}
BigInteger first = BigInteger.ZERO;
BigInteger second = BigInteger.ONE;
BigInteger temp;
for (int i = 1; i < n; i++) {
temp = first.add(second);
first = second;
second = temp;
}
return second.mod(BigInteger.TEN).intValue();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(getFibonacciLastDigitNaive(n));
}}
如果输入 = 613455,我的代码将失败,获取值需要 30 秒,最大允许时间为 1.5 秒。
我不得不使用大整数,因为 long 不够。
【问题讨论】:
-
我不明白.. 约束说 n
-
如果我阻止他输入超过 107 个测试用例失败,我不知道为什么会发生这种情况,所以我不得不删除这个约束
-
是的,它注定要失败,不是吗?这意味着不会有任何高于 107 的输入。此外,您不需要大数字。 @meowgoesthedog 的提示非常好。
-
我预计“107”应该是 10⁷。我进行了修改以解决问题。
标签: java algorithm fibonacci biginteger