斐波拉契的兔子

package cn.gl.program25;

import java.util.Scanner;

/**
 * 题目:
 *     古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生对兔子,假如兔子不死,
 *  问每个月兔子总数为多少?
* @author 冷夜雨花未眠 E-mail:[email protected]
* @version 创建时间:2019年11月11日
 */
public class Demo1 {
    public static void main(String[] args) {
        
        System.out.println("第1个月的兔子对数:1");
        System.out.println("第2个月的兔子对数:1");
        int f1 = 1, f2 = 1, f, M = 24;//设置最大月数为24
        for (int i = 3; i <= M; i++) {
            f = f2;
            f2 = f1 + f2;
            f1 = f;
            System.out.println("第" + i + "个月的兔子对数:" + f2);
        }
    }
}

这是第一种方法    

数列:1,1,2,3,5,8,13,21,34,55,89,144,233,·…它是一个线性递归数列

package cn.gl.program25;

import java.util.Scanner;

/**
 * 题目:
 *     古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生对兔子,假如兔子不死,
 *  问每个月兔子总数为多少?
* @author 冷夜雨花未眠 E-mail:[email protected]
* @version 创建时间:2019年11月11日
 */
public class Demo1 {
    public static void main(String[] args) {
        
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        System.out.println("请输入查询第几个月的兔子对数:");
        System.out.println("总对数为:" + "\n" + f(n) + "对");

    }

    public static int f(int n) {
    
            if (n != 1 && n != 2) {
                return f(n - 1) + f(n - 2);
            } else
                return 1;
    
        
    }
}

这是第二种方法

猜你喜欢

转载自www.cnblogs.com/gl0102/p/11839125.html