Calculate the first N terms of the Fibonacci sequence

 

The Fibonacci sequence refers to a sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, …

This sequence starts from the third term, and each term is equal to the sum of the first two terms.

Output the first N terms of this sequence (N>2).

Define a sequence, assign the first two terms a value of 1, then loop N-2 times, taking the last and second to last terms respectively, and append their sum to the sequence. The result is the generated Fibonacci sequence.

Using recursive algorithm:


A

B

C

1

30

[1,1]


2

for A1-2

=B1.m(-1)+B1.m(-2)

>B1|=B2

http://try.scudata.com.cn/try.jsp?splx=ExA002jsfbnqsl1.splx

A1 is the value of N, and an initial sequence [1,1] is created in B1.

A2 loops N-2 times, B2 calculates the sum of the last two terms in the sequence, and C2 appends the new value to the original sequence. After the loop is completed, the final result can be seen in B1.

In SPL, a for loop is used to facilitate the viewing of the calculation results for each step. Using A.m (n) can take values from the sequence by position, when n is negative counting from back to front; A =A|a makes it easy to add members after the sequence.

We can also use loop functions to calculate:


A

B

C

1

30

>a=0,b=1


2

=A1.(b=a+b,a=b-a)



http://try.scudata.com.cn/try.jsp?splx=ExA002jsfbnqsl2.splx

In B1, the initial value of the parameters required for calculation is defined as a=0, b=1. A2 uses a loop function to sequentially calculate N values in the sequence. Each time a+b is calculated, a new b is obtained. Subtracting a from the new b yields the original value of b as the current value in the sequence, which is then assigned to a. After execution, the final result can be obtained in A2.

The loop function in SPL can implement calculations that require multiple cells or even lines in a for loop using one cell, resulting in simpler code. Using the comma operator a,b,…, the expression a,b,… will be calculated sequentially, and return the last result. In fact, the code can even be simplified into an expression: =a=0,b=1,30.(b=a+b,a=b-a)


A

B

C

1

30


=fibonacci(A1)

2

func fibonacci(n)

if n < 3

return [1]*n

3


=fibonacci(n-1)

return B3|(B3.m(-1)+B3.m(-2))

http://try.scudata.com.cn/try.jsp?splx=ExA002jsfbnqsl3.splx

First, let's take a look at the subroutine defined in block A2, named fibonacci, which uses a parameter n to represent the number of items. In B2, if n is less than 3, return an n-item sequence consisting of 1; When n 3, recursively call the subroutine in B3 to obtain the Fibonacci sequence of n-1 terms, and then add a new term in C3 to return the result of n terms.

In C1, the desired result can be obtained directly using=fibonacci (N).

In SPL, calling code through subroutines can be very concise, especially when subroutines need to be reused.

The results obtained using the above three methods are the same:

..