古典兔子问题

非递归算法

 1 package com.laurdawn;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         rabbit(getInteger());
10     }
11 
12     public static void rabbit(int month) {
13         if (month > 1){
14             System.out.println("第1月份" + "兔子总数:1对");
15             if(month >2){
16                 System.out.println("第2月份" + "兔子总数:1对");
17                 long x = 1, y = 1;
18                 for (int i = 3; i <= month; i++) {
19                     if(i%2 != 0){
20                         x = x + y;
21                         System.out.println("第" + i + "月份" + "兔子总数:" + x + "对");
22                     }
23                     if(i%2 == 0){
24                         y = x + y;
25                         System.out.println("第" + i + "月份" + "兔子总数:" + y + "对");
26                     }
27                 }
28             }
29         }
30         if (month < 0) {
31             System.out.println("月份错误,请重新输入!");
32             rabbit(getInteger());
33         }
34 
35     }
36 
37     public static int getInteger() {
38         System.out.println("请输入月份:");
39         Scanner s = new Scanner(System.in);
40         return s.nextInt();
41     }
42 }
原文地址:https://www.cnblogs.com/laurdawn/p/5631936.html