📜  fibo 20 (1)

📅  最后修改于: 2023-12-03 15:00:44.973000             🧑  作者: Mango

Fibo 20

Introduction

"Fibo 20" refers to finding the 20th number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers. The sequence starts with 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on. The 20th number in the Fibonacci sequence is 6765.

Implementation

There are many ways to implement a program that finds the 20th number in the Fibonacci sequence.

Using recursion

One way to implement a program that finds the 20th number in the Fibonacci sequence is to use recursion. Recursion is a technique in which a function calls itself.

def fibo(n):
    if n <= 1:
        return n
    else:
        return fibo(n-1) + fibo(n-2)

result = fibo(20)
print(result) # Output: 6765

In this implementation, we define a function called fibo that takes an argument n. If n is less than or equal to 1, we return n. If n is greater than 1, we call the fibo function recursively with n-1 and n-2 as arguments, and add the results together to get the Nth number in the Fibonacci sequence.

Using iteration

Another way to implement a program that finds the 20th number in the Fibonacci sequence is to use iteration. Iteration is a technique in which a loop is used to repeat a set of instructions.

def fibo(n):
    if n <= 1:
        return n
    else:
        a = 0
        b = 1
        for i in range(2, n+1):
            c = a + b
            a = b
            b = c
        return b

result = fibo(20)
print(result) # Output: 6765

In this implementation, we define a function called fibo that takes an argument n. If n is less than or equal to 1, we return n. If n is greater than 1, we use a loop to iterate from 2 to n+1. In each iteration, we add a and b together to get c, and then update a and b to be the previous two numbers in the Fibonacci sequence. After the loop has finished, we return b, which is the Nth number in the Fibonacci sequence.

Conclusion

In conclusion, "Fibo 20" refers to finding the 20th number in the Fibonacci sequence. There are many ways to implement a program that finds this number, including using recursion and iteration. The code examples above demonstrate two common ways to implement such a program in Python.