Home  >  Article  >  Backend Development  >  Detailed explanation of C++ function recursion: recursive implementation of factorial and Fibonacci sequences

Detailed explanation of C++ function recursion: recursive implementation of factorial and Fibonacci sequences

王林
王林Original
2024-05-02 13:24:011005browse

Recursion is a programming technique for function self-calling, which is divided into baseline conditions and recursive calls. Using recursion you can implement factorial, which is a positive integer multiplied by the product of all its smaller positive integers, and Fibonacci sequence, which is a sequence in which each number is the sum of the previous two numbers.

C++ 函数递归详解:递归实现阶乘和斐波那契数列

Detailed explanation of C function recursion: Recursive implementation of factorial and Fibonacci sequences

Introduction

Recursion is a programming technique that allows a function to call itself to solve a problem. Recursive functions are usually divided into two parts: baseline conditions and recursive calls.

Recursive implementation of factorial

Factorial is the product of a positive integer multiplied by all its smaller positive integers. For example, the factorial of 5 is equal to 5 x 4 x 3 x 2 x 1 = 120.

int阶乘(int n) {
  if (n == 0) {  // 基线条件
    return 1;
  } else {
    return n * 阶乘(n - 1);  // 递归调用
  }
}

Practical case: Calculate the factorial of 10

int result = 阶乘(10);
cout << "10 的阶乘为 " << result << endl;

Output:

10 的阶乘为 3628800

Recursive implementation of Fibonacci sequence

The Fibonacci sequence is a sequence of numbers in which each number is the sum of the previous two numbers. The sequence starts with 0 and 1.

int斐波那契(int n) {
  if (n == 0) {  // 基线条件
    return 0;
  } else if (n == 1) {
    return 1;
  } else {
    return 斐波那契(n - 1) + 斐波那契(n - 2);  // 递归调用
  }
}

Practical case: Print the first 10 numbers of the Fibonacci sequence

for (int i = 0; i < 10; i++) {
  cout << 斐波那契(i) << " ";
}

Output:

0 1 1 2 3 5 8 13 21 34

The above is the detailed content of Detailed explanation of C++ function recursion: recursive implementation of factorial and Fibonacci sequences. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn