【问题标题】:Large FIbonacci Java Time Exceeded超过大的 FIbonacci Java 时间
【发布时间】: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。)

请指导我。

此致, 维迪特·沙阿

【问题讨论】:

  • 看起来你只是想返回一个大斐波那契数的最后一位。那么为什么不使用 intshort 而不是 BigInteger 来完成 mod 10 中的所有算术呢?
  • 您可以做的另一件事是利用最后一位数字的模式每 60 个斐波那契数重复一次这一事实 - 因此您可以使用 n % 60 代替 n 作为 @ 的参数987654327@.
  • 不是重复的,@PeterdeRivaz - 在这里,OP 正在寻找答案 mod 10,这使它成为一个完全不同的问题。
  • 哇!代码与标记的 dup 逐字节相同。不过我不知道那是什么意思……
  • @DavidWallace 道歉:我没有发现模数可以让您更优雅的解决方案成为可能 - 我已按要求重新提出问题。

标签: java algorithm fibonacci


【解决方案1】:

我从 cmets 中提取了最容易实现的建议并将其放入代码中。

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) {
        int m = 10;
        BigInteger sixty = new BigInteger("60");
        int k = (n.mod(sixty)).intValue();
        int ans = 0;

        if(k == 0) {
            ans = 0;
        } else if(Math.abs(k) <= 2) {
            ans = 1;
        } else {
            int km1 = 1;
            int km2 = 1;

            for(int i = 3; i <= Math.abs(k); ++i) {
                ans = (km1 + km2)%m;
                km2 = km1;
                km1 = ans;
            }
        }

        if(k<0 && k%2==0) { ans = -ans; }
        return new BigInteger("" + ans);
    }

}

【讨论】:

    【解决方案2】:

    试试看:

    public static int fibonacci(int n) {
        return (int)((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow((1 - Math.sqrt(5)) / 2, n)) / Math.sqrt(5));
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 2011-10-18
      • 2021-03-12
      • 2020-04-29
      • 2013-04-01
      • 1970-01-01
      • 2022-01-19
      • 2019-04-07
      相关资源
      最近更新 更多