当前位置: 首页 > news >正文

C语言斐波那契数列的多样实现

在C语言中,斐波那契数列可以通过多种方法实现,包括递归、动态规划、矩阵快速幂等。以下是一些常见的实现方法:

1. 递归实现

递归是实现斐波那契数列最直接的方法,但效率较低,因为会重复计算许多子问题。

#include <stdio.h>// 递归函数计算斐波那契数列的第n项
int fibonacci(int n) {if (n <= 1) {return n; // 基础情况:F(0) = 0, F(1) = 1} else {return fibonacci(n - 1) + fibonacci(n - 2); // 递归情况}
}int main() {int n;printf("Enter the term number: ");scanf("%d", &n);printf("The %dth term of the Fibonacci sequence is: %d\n", n, fibonacci(n));return 0;
}

2. 动态规划实现

动态规划方法通过存储已计算的斐波那契数来避免重复计算,从而提高效率。

#include <stdio.h>// 动态规划函数计算斐波那契数列的第n项
int fibonacci(int n) {if (n <= 1) {return n; // 基础情况:F(0) = 0, F(1) = 1}int fib[n + 1]; // 创建一个数组来存储斐波那契数fib[0] = 0; // 初始化基础情况fib[1] = 1;for (int i = 2; i <= n; i++) {fib[i] = fib[i - 1] + fib[i - 2]; // 动态规划计算}return fib[n]; // 返回第n项
}int main() {int n;printf("Enter the term number: ");scanf("%d", &n);printf("The %dth term of the Fibonacci sequence is: %d\n", n, fibonacci(n));return 0;
}

3. 矩阵快速幂实现

矩阵快速幂方法可以将计算斐波那契数列的时间复杂度降低到O(log n)。

#include <stdio.h>
#include <stdlib.h>// 定义2x2矩阵
typedef struct {int a[2][2];
} Matrix;// 矩阵乘法
Matrix multiply(Matrix m1, Matrix m2) {Matrix result;for (int i = 0; i < 2; i++) {for (int j = 0; j < 2; j++) {result.a[i][j] = m1.a[i][0] * m2.a[0][j] + m1.a[i][1] * m2.a[1][j];}}return result;
}// 矩阵快速幂
Matrix power(Matrix base, int n) {Matrix result = {{1, 0}, {0, 1}}; // 单位矩阵while (n > 0) {if (n % 2 == 1) {result = multiply(result, base);}base = multiply(base, base);n /= 2;}return result;
}// 计算斐波那契数列的第n项
int fibonacci(int n) {Matrix base = {{1, 1}, {1, 0}};Matrix result = power(base, n);return result.a[0][1];
}int main() {int n;printf("Enter the term number: ");scanf("%d", &n);printf("The %dth term of the Fibonacci sequence is: %d\n", n, fibonacci(n));return 0;
}

4. 通项公式实现

斐波那契数列的通项公式(Binet公式)可以直接计算第n项,但可能会出现精度问题。

#include <stdio.h>
#include <math.h>// 通项公式计算斐波那契数列的第n项
int fibonacci(int n) {double phi = (1 + sqrt(5)) / 2; // 黄金分割比double psi = (1 - sqrt(5)) / 2; // 黄金分割比的共轭return (int)round((pow(phi, n) - pow(psi, n)) / sqrt(5));
}int main() {int n;printf("Enter the term number: ");scanf("%d", &n);printf("The %dth term of the Fibonacci sequence is: %d\n", n, fibonacci(n));return 0;
}

以上是C语言中实现斐波那契数列的几种常见方法,每种方法都有其优缺点,适用于不同的场景。在实际应用中,可以根据需要选择合适的实现方法。


http://www.mrgr.cn/news/98247.html

相关文章:

  • OpenHarmony5.0.2 USB摄像头适配
  • Java面向对象核心:多态、抽象类与接口实战解析
  • 基于51单片机的正负5V数字电压表( proteus仿真+程序+设计报告+讲解视频)
  • c语言 open函数
  • C语言中冒泡排序和快速排序的区别
  • 02核心-EffectSpec,EffectContext
  • Excel表格文件分组归并——通过sql
  • Sklearn入门之datasets的基本用法
  • Android Studio 在 Windows 上的完整安装与使用指南
  • 八大定位UI
  • 从宇树摇操avp_teleoperate到unitree_IL_lerobot:如何基于宇树人形进行二次开发(含Open-TeleVision源码解析)
  • 【HD-RK3576-PI】系统更新与恢复
  • CSI-PVController-claimWorker
  • Linux上位机开发实践(OpenCV算法硬件加速)
  • 【redis进阶三】分布式系统之主从复制结构(1)
  • 【复旦微FM33 MCU 底层开发指南】高级定时器ATIM
  • NoSQL入门指南:Redis与MongoDB的Java实战
  • 2025蓝桥杯python A组题解
  • 数据库事务管理:ACID特性与隔离级别的深度解读
  • QScrCpy源码解析(4)获取手机端数据知识补充