zoukankan      html  css  js  c++  java
  • 非递归斐波那契

    求第100个斐波那契数

    package utils;

    import java.math.BigInteger;

    public class FibTest {
     public static void main(String[] arags) {
      int fibNum = 100;
      System.out.println(fib(fibNum));
     }

     /*
      * public static long fib(int n) { if (n < 3) return 1; else { long a = 1;
      * long b = 1; for (int i = 2; i < n - 1; i++) { b = a + b; a = b - a;
      * System.out.println("a = " + a + "  b = " + b); } return a + b; } }
      */

     public static BigInteger fib(int n) {
      if (n < 3)
       return BigInteger.ONE;
      else {
       BigInteger a = BigInteger.ONE;
       BigInteger b = BigInteger.ONE;
       for (int i = 2; i < n - 1; i++) {
        b = a.add(b);
        a = b.subtract(a);
    //    System.out.println("a = " + a + "  b = " + b);
       }
       return a.add(b);
      }
     }
    }

     

    测试结果:354224848179261915075

  • 相关阅读:
    IEnumerator & IEnumerable
    GameObject.Active
    Unity3D的四种坐标系
    gvim
    Platform Dependent Compilation
    delegate
    new 约束
    UIPanel
    UIButton
    UISprite
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3266434.html
Copyright © 2011-2022 走看看