Algorithm - Recursively Generate Fibonacci Sequence

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

提示:这里可以添加本文要记录的大概内容:

For example: With the continuous development of artificial intelligence, the technology of machine learning is becoming more and more important. Many people have started to learn machine learning. This article introduces the basic content of machine learning.


提示:以下是本篇文章正文内容,下面案例可供参考

1. Recursively generate the Fibonacci sequence

F(n) = F(n-1) + F(n-2)

2. Use steps

1. Pseudocode

The code is as follows (example):

fibonacci(n):       // n 表示求数列中第 n 个位置上的数的值
    if n == 1:        // 设置结束递归的限制条件
        return 1
    if n == 2:        // 设置结束递归的限制条件
        return 1
    return fibonacci(n-1) + fibonacci(n-2)    // F(n) = F(n-1) + F(n-2)

2.c

The code is as follows (example):

#include <stdio.h>
// index 表示求数列中第 index 个位置上的数的值
int fibonacci(int index) {
    
    
    // 设置结束递归的限制条件
    if (index == 1 || index == 2) {
    
    
        return 1;
    }
    // F(index) = F(index-1) + F(index-2)
    return fibonacci(index - 1) + fibonacci(index - 2);
}
int main()
{
    
    
    int i;
    // 输出前 10 个数
    for (i = 1; i <= 10; i++) {
    
    
        printf("%d ", fibonacci(i));
    }
    return 0;
}

Summarize

The following provides you with a pseudo-code to implement the Fibonacci sequence in a common way:
//Continuously output the Fibonacci sequence with a length of n

fibonacci(n):
    num1 <- 1    // 设置 num1 的初值为 1
    num2 <- 1    // 设置 num2 的初值为 1
    for i<-1 to n:
        Print(num1)              // 输出 num1 的值
        nextNum <- num1 + num2   // 将 num1+num2 的值赋值给 nextNum
        num1 <- num2             // num2 的值赋值给 num1
        num2 <- nextNum          // nextNum 的值赋值给 num2
        ```

Guess you like

Origin blog.csdn.net/lianghuajunone/article/details/123412409