Fibonacci非递归实现

先上递归实现

public static long recursive(long n) {
  if (n == 1 | n == 2) {
    return 1;
  } else {
    return recursive(n - 2) + recursive(n - 1);
  }
}

非递归实现

public static long non_recursive(long n) {
  long first = 1;
  long second = 1;
  long last = 0;
  for (int i = 1; i <= n; i++) {
    if (i == 1 | i == 2) {
      last = 1;
    } else {
      last = first + second;
      first = second;
      second = last;
    }
  }
  return last;
}

  

posted @ 2017-04-18 11:15  暴走の考拉  阅读(232)  评论(0)    收藏  举报