The number of rabbit problem (Fibonacci number)

Classical problem: a pair of rabbits from the first birth 3 from months gave birth to a monthly one pair of rabbits, bunnies grow up to the third month after the month gave birth to one pair of rabbits, if the rabbit is not dead, and asked each the total number of rabbits month for how much?
Program analysis: number of rabbits law column 1,1,2,3,5,8,13,21 ....

1. recursive solution:

dataStruct Package; 
Import java.util.Scanner; 

/ ** 
 * @ClassName: RabbitDG 
 * @Description: the TODO 
 * @author: hunterm 
 * @date: 2019/8/5 16:00 
 * @Version: 1.0 
 * / 
public class RabbitDG { 
    Long SUM = 0; 
    public static void main (String [] args) { 
        System.out.println ( "Please enter the number of months ..."); 
        Scanner Scanner new new SC = (the System.in); 
        Long months = SC. the nextLong (); 
        System.out.println ( "first" + months + "months, the number of the rabbit is:" + new new RabbitDG () getRabbitSum (months).); 
    } 
    / ** 
     * recursive method 
     * 1123 13 is 21 is. 8. 5 
     * /  
    public Long getRabbitSum (Long months) {
        IF (|| months months. 1 == == 2) {
            return 1;
        }else{
            return sum = getRabbitSum(months - 1) + getRabbitSum(months - 2);
        }
    }
}

  2. Non-recursive solution

package dataStruct;

import java.util.Scanner;
/**
 * @ClassName: Rabbit
 * @Description: TODO
 * @Author: hunterm
 * @Date: 2019/8/5 15:46
 * @Version:1.0
 */
public class Rabbit {
    public static void main(String[] args) {
        System.out.println("请输入月数...");
        Scanner sc = new Scanner(System.in);
        long months = sc.nextLong();
        System.out.println("第"+months+"个月,兔子的对数为:"+new Rabbit().get(months));
    }
    /**
     * 规律:1 1 2 3 5 8 13 21
     */
    public long get(long months) {
        long f1 = 1L;
        long f2 = 1L;
        long f = 0;
        if(months == 1 || months == 2){
            return 1;
        }
        for (int i = 3; i <= months; i++) {
            f = f2;
            f2 = f1 + f2;
            f1 = f;
        }
        return f2;
    }
}

  Recursive method it will, it is generally investigate non-recursively solving the interview.

  

Guess you like

Origin www.cnblogs.com/maohaitao/p/11305861.html