Linear recurrent sequence algorithm problem

A linear recurrent sequence

       When the number of columns (sequence) \ (A_N \) satisfies \ (A_N \) by \ (A_N \) before k pieces of linear generation, called \ (A_N \) is a linear recursive sequences, that is:
\ [A_N = b_1a_ {n- -1} + b_2a_ {n-2 } + ... + b_ka_ {nk} \]

        Wherein \ (B_i \) is a constant

  • + Fast matrix multiplication using powers principle can be answered in O (logN) time
  • Sequence by using the formula can answer in O (1) time

2 Python Code

That deed to the number of columns Fibonacci number sequence as an example

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\t cost time(1E-6s):%d" % (n, F_n, (t1_e - t1_s).microseconds))

Figure 1 shows the code runs

Guess you like

Origin www.cnblogs.com/Kalafinaian/p/11546178.html