斐波那契数和优化
作者:互联网
package pqs; /** * 0 1 2 3 4 * 0 1 1 2 3 5 8 13... * 斐波那契数即前两项相加 */ public class feibonaqishu { /** * 递归 * @param n * @return */ public static int fib1(int n){ if (n <= 1) return n; return fib1(n-1) + fib1(n-2); } /** * 优化的算法 * @param n * @return */ public static int fib2(int n){ if (n <= 1) return n; int first = 0; int second = 1; for (int i=0; i < n -1;i++){ int sum = first + second; first = second; second = sum; } return second; } public static void main(String[] args) { System.out.println(fib2(1)); } }
标签:契数,13,return,int,斐波,优化,public 来源: https://www.cnblogs.com/pace/p/15864477.html