【发布时间】:2017-04-11 21:03:59
【问题描述】:
我被困在一个测试用例上。 这个问题需要在给定的时间段内计算一个大的斐波那契数。 我已经通过了 10 个案例中的 8 个案例并坚持了 9 个。
这是我的代码:
import java.util.*;
import java.math.BigInteger;
public class LastNumberofFibo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger bi = sc.nextBigInteger();
System.out.println(fib(bi));
}
public static BigInteger fib(BigInteger n) {
BigInteger val=new BigInteger("10");
int k = n.intValue();
BigInteger ans = null;
if(k == 0) {
ans = new BigInteger("0");
} else if(Math.abs(k) <= 2) {
ans = new BigInteger("1");
} else {
BigInteger km1 = new BigInteger("1");
BigInteger km2 = new BigInteger("1");
for(int i = 3; i <= Math.abs(k); ++i) {
ans = km1.add(km2);
km2 = km1;
km1 = ans;
}
}
if(k<0 && k%2==0) { ans = ans.negate(); }
return ans.mod(val);
}
}
提交后我得到以下超时结果。
我需要帮助来提高我的代码效率。
反馈:
失败案例 #9/10:超过时间限制 输入: 613455
你的输出:
标准错误:
(使用时间:3.26/1.50,使用内存:379953152/536870912。)
请指导我。
此致, 维迪特·沙阿
【问题讨论】:
-
看起来你只是想返回一个大斐波那契数的最后一位。那么为什么不使用
int或short而不是BigInteger来完成 mod 10 中的所有算术呢? -
您可以做的另一件事是利用最后一位数字的模式每 60 个斐波那契数重复一次这一事实 - 因此您可以使用
n % 60代替n作为 @ 的参数987654327@. -
不是重复的,@PeterdeRivaz - 在这里,OP 正在寻找答案 mod 10,这使它成为一个完全不同的问题。
-
哇!代码与标记的 dup 逐字节相同。不过我不知道那是什么意思……
-
@DavidWallace 道歉:我没有发现模数可以让您更优雅的解决方案成为可能 - 我已按要求重新提出问题。