For JS beginners, the Fibonacci sequence has always been a headache, and the idea is never clear.
Hope to read this article will be helpful to you.
What is the Fibonacci sequence:
A: Fibonacci series, also known as the Golden section of the series, because the mathematician Leonardo's Fibonacci (Leonardoda Fibonacci) to the rabbit breeding as an example of the introduction, it is also known as the "Rabbit series."
Refers to a series of: 0, 1, 1, 2, 3, 5, 8, 13, 21, 、......
Question: One person wants to know how many pairs of rabbits can breed in a year? So he built a fence and locked a pair of rabbits in it. It is known that a pair of rabbits can have a pair of rabbits each month, and a pair of rabbits from the 3rd month after the birth of a pair of rabbits a month. If there is no death in a year, how much can a pair of rabbits breed in a year (12 months)? The law of known rabbits is a series: 1,1,2,3,5,8,13,21 ...
A: first we need to know the needs and steps of this problem
Requirements: The current item of a sequence is equal to the sum of the first two items. 12th.
Steps:
1. Define three variables, and then two initialize the values. The third is used as a storage
2. First the second variable is stored into the third variable summary, the second variable is re-assigned to the first and second of the sum
3. Assign a stored third variable to the first variable.
4. Execute 12 times (because the first two items do not need to be calculated, so only 10 times are required).
Analytical:
1. Define three variables, and then two initialize the values. The third is used as a storage
We can think of this sequence as a push-box game.
2. First store the second variable into the third variable
The second variable is then re-assigned as the sum of the first and second values.
3. Assign a stored third variable to the first variable.
And so on to the last item
Use the For Loop code as follows:
//1. Define three variables, and then two initialize the values. The third is used as a storage vartemp; varNUM1 = 1; varnum2 = 1; //2. First the second variable is stored into the third variable summary, the second variable is re-assigned to the first and second of the sum for(vari=1;i<=10;i++) {Temp=num2; Num2= Num1 +num2; //3. Assign a stored third variable to the first variable. NUM1 =temp; //4. Execute 10 times. (because the first two items do not need to be calculated, it only needs to be performed 10 times)} alert (num2);
Thanks for watching, hope to help you!
JS Fibonacci sequence (rabbit problem)