Java Practice question: rabbit problem

Source: Internet
Author: User

Java Practice question: rabbit problem

This question is also called the Fibonacci sequence (Fabonacci), the first person to study the series is the Leonardo of Pisa (also known as the Fibonacci), which he used to describe the number of rabbits growing. The first month there are a couple of newborn rabbits. After the second month, they can have babies. Every month a pair of fertile rabbits will be born, and a new rabbit would never die.

Suppose that in the N month there are newborn and fertile rabbits in total a pairs, n+1 month has a total of b pairs. In n+2 months there must be a total of a+b pairs: Because during the n+2 months, all a pairs of rabbits that had existed in n months were already fertile and gave birth to a pair of offspring, while in the previous January (n+1 month) of B for Rabbits, the newly born rabbits were not fertile in the month. Refer to the following table:

, @

The number of months passed

1

2

3

4

5

6

7

8

9 [] /td>

All

[

New born rabbit

0

0

1

1

2

P>3

5

8

34

@

+

Rabbit log

1

1

2

3

5

8

,

$

144

This can be defined by mathematical induction as:

F (n) = f (n-1) +f (n+1);(n>2,f (1) =1,f (2) =1);

What if we use the normal iterative method to implement it? Let's say we want to print the logarithm of the 12-month rabbit, the code reads:

	public static void Main (String args[]) {
		
		int r[] = new INT[12];  Number of rabbits per month
		
		r[0] = 1;  Number of rabbits in the first month
		
		r[1] = 1;  The Rabbit book for the second month for
		
		(int a = 2; a < a++) {
			R[a] = R[a-1] + r[a-2];  
			System.out.println (R[a]);
		}
	


The code is simple, it is implemented in arrays, but if we use recursion, the code is simpler:

	public static void Main (String args[]) {
		System.out.println (FBI (12));//Print
	}
	
	static int Fbi (int i) {
		if (I < 2) return i==0?0:1;
		Return to the FBI (I-1) + FBI (I-2); Call your own function
	}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.