多少只兔子

79 阅读1分钟

古典问题

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一 只兔子,假如兔子都不死,问每个月的兔子总数为多少?

分析

  • 第一月有 1只
  • 第二月有 1只
  • 第三月有 2只
  • 第四月有 3只
  • 第五月有 5只
  • 第六月有 8只
  • 第七月有 13只
  • 第八月有 21只 从第三月起,每月的兔子是前两月的和:X(n) = X(n-1) + X(n-2)

代码

第一种:循环方式

function f(month) {
  if (month<3) {
    return 1
  } else {
    let dat1 = 1;
    let dat2 = 1;
    let res = 0
    for(let i = 0; i<month - 2; i++) {
      res = dat1 + dat2
      dat1 = dat2;
      dat2 = res
    }
    return res
  }
}
console.log(f(9))

第二种递归

function f1(month) {
  if (month<3) {
    return 1
  } else {
    return f(month-1) + f(month - 2)
  }
  
}
console.log(f1(8))