zoukankan      html  css  js  c++  java
  • 线性递归数列算法题

    1 线性递归数列

           若数列(序列)(a_n) 满足(a_n)可由(a_n)前k项线性生成,则称(a_n)是线性递归数列,即有:

    [a_n = b_1a_{n-1} + b_2a_{n-2} + ... + b_ka_{n-k} ]

            其中(b_i)是常数

    • 使用矩阵乘法 + 快速幂原理可以在O(logN)时间内得到答案
    • 使用数列通项公式可以在O(1)时间内得到答案

    2 Python代码

    以斐波那契数列数列为例说明

    import numpy as np
    import datetime
    
    A = [[1,1], [1, 0]]
    a1 = [[1],[1]]
    
    mat_a1 = np.asarray(a1)
    
    
    for n in range(3, 39+1):
        # 矩阵乘法 + 快速幂
        t1_s = datetime.datetime.now()
        mat_R = np.asarray([[1,0], [0,1]])
        mat_A = np.asarray(A)
    
        r = n - 2
        while r > 0 :
            if r & 1 == 1:
                mat_R = mat_R.dot(mat_A)
            mat_A = mat_A.dot(mat_A)
            r >>= 1
    
        F_n = mat_R.dot(mat_a1)[0][0]
        t1_e = datetime.datetime.now()
        print("F_%d = %d	 cost time(1E-6s):%d" % (n, F_n, (t1_e - t1_s).microseconds))
    

    图1 代码运行展示
  • 相关阅读:
    Python_堡垒机开发基础
    用haslib给字符加密
    python学习(集合)
    编码
    小练习03
    python学习(字典)
    小练习02
    python学习(列表,元祖)
    小练习
    python学习
  • 原文地址:https://www.cnblogs.com/Kalafinaian/p/11546178.html
Copyright © 2011-2022 走看看