代码改变世界

矩阵求幂-倍加算法

2019-03-14 15:21  生活的味道  阅读(665)  评论(0编辑  收藏  举报
 1 def mul_add2(n,t):
 2     ret=[]
 3     while t>=1:
 4         ret.insert(0,t%2)
 5         print(t)
 6         t=int(t/2)
 7     print(ret)
 8     ans = 1
 9     for i in ret:
10         if i==0:
11             ans=ans*ans
12         else:
13             ans=n*ans*ans
14     print(ans)
15 
16 
17 import numpy as np
18 
19 def mul_add(A,t):
20     ret=[]
21     while t>=1:
22         ret.insert(0,t%2)
23         print(t)
24         t=int(t/2)
25     print(ret)
26     B = np.array([1,1])
27     T=np.array([[1,0],[0,1]])
28     for i in ret:
29         T=np.matmul(T,T)
30         if i!=0:
31             T=np.matmul(T,A)
32 
33     print(np.matmul(A,B))