Classic recursive algorithm written in java

 

 
// adding 1 to 100:
public static void main (String [] args) { System.out.println (F ( 100 )); } // recursive public static int F ( int X) { IF (X <2 ) { return . 1 ; } the else { return F (. 1-X) + X; } }

 

 

2. Fibonacci number column that deed raw rabbit

Title: Classical problem: every month from 3 months birth to a rabbit, a small rabbit to grow the third month after the month gave birth to one pair of rabbits, if the rabbit is not dead, and asked how much of the total number of rabbits per month ?

Analysis: First, we need to understand the meaning of the title refers to the total number of rabbits per month; suppose the rabbit into small medium large are three rabbits from three months after birth will give birth to a pair of rabbits each month,

So we assume that the first month of a small rabbit rabbit, the rabbit is the second month, after the first three months as a big rabbit, then there are 1,0,0, respectively, in the first month, second month, respectively 0,1,0,

The first three months were 1,0,1, respectively, for the fourth month, 1,1,1, 2,1,2, respectively the fifth month, the sixth month respectively 3,2,3, first Seven months were five, three ......

The total number of rabbits are: 1, 1, ......

So come to a law, starting from the first three months , the total number of rabbits behind are equal to the total number of the previous two months and a rabbit, is the Fibonacci number.

 

 public  static  void main (String [] args) {
         for ( int I =. 1; I <= 12 is; I ++ ) { 
            System.out.println ( "first" + i + "rabbit months were" + f (i) + " on " ); 
        } 
    } 
    // recursive 
    public  static  int F ( int X) {
       IF (X <. 3 ) {
           return . 1 ; 
      } the else {
        return   F (. 1-X) + F (X-2 ); 
      } 
    }

 

Guess you like

Origin www.cnblogs.com/zxrxzw/p/11425013.html