解析分别用递归与循环的方式求斐波那契数列的实现方法_java

分享到:

代码如下:

public class Fibonacci {

 public static long recursive(int n) {
  if (n <= 0)
   return 0;
  if (n == 1)
   return 1;
  return recursive(n - 1) + recursive(n - 2);
 }

 public static long loop(int n) {
  if (n <= 0)
   return 0;
  if (n == 1)
   return 1;
  long fib1 = 0;
  long fib2 = 1;
  long sum = 0;
  for (int i = 2; i <= n; i++) {
   sum = fib1 + fib2;
   fib1 = fib2;
   fib2 = sum;
  }
  return sum;
 }
}


用递归的方式的效率远远不如循环!

昵    称:
验证码: