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

C语言 | Leetcode C语言题解之第508题斐波那契数

题目:

题解:

struct Matrix {
    int mat[2][2];
};

struct Matrix matrixMultiply(struct Matrix* a, struct Matrix* b) {
    struct Matrix c;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            c.mat[i][j] = (*a).mat[i][0] * (*b).mat[0][j] + (*a).mat[i][1] * (*b).mat[1][j];
        }
    }
    return c;
}

struct Matrix matrixPow(struct Matrix a, int n) {
    struct Matrix ret;
    ret.mat[0][0] = ret.mat[1][1] = 1;
    ret.mat[0][1] = ret.mat[1][0] = 0;
    while (n > 0) {
        if (n & 1) {
            ret = matrixMultiply(&ret, &a);
        }
        n >>= 1;
        a = matrixMultiply(&a, &a);
    }
    return ret;
}

int fib(int n) {
    if (n < 2) {
        return n;
    }
    struct Matrix q;
    q.mat[0][0] = q.mat[0][1] = q.mat[1][0] = 1;
    q.mat[1][1] = 0;
    struct Matrix res = matrixPow(q, n - 1);
    return res.mat[0][0];
}

http://www.kler.cn/news/366692.html

相关文章:

  • 鸿蒙开发初级证书考试答案
  • 【Axure高保真原型】分级树筛选中继器表格
  • ACL访问控制
  • Visual studio 下载安装
  • 找不到包的老版本???scikit-learn,numpy,scipy等等!!
  • 死锁(Deadlock)C#
  • 24. Lammps命令学习-系统定义部分总结
  • MySQL-日志
  • qt QWidget详解
  • LeetCode刷题日记之贪心算法(五)
  • Vim 编辑器从入门到入土
  • Ubuntu安装repo
  • 基于plc的楼宇自动化控制系统(开题报告)
  • 构建高效房屋租赁平台:SpringBoot应用案例
  • 07_Linux网络配置与管理:命令与工具指南
  • 【华为HCIP实战课程二十一】OSPF区域间汇总配置详解,网络工程师
  • Linux命令笔记
  • jenkins 自动化部署Springboot 项目
  • 物联网数据采集网关详细介绍-天拓四方
  • 跨境支付,哪些国产数据库能接得住?
  • 为什么要使用网络IO内存数据库?
  • 名词(术语)了解--柯里化(Currying)
  • spark读取parquet文件
  • 常见的音视频格式介绍
  • Cilium + ebpf 系列文章- (七)Cilium-LoadBalancer类型的SVC的IPPool
  • 总裁主题CeoMax-Pro主题7.6开心版