码迷,mamicode.com
首页 > 其他好文 > 详细

Fast Power

时间:2019-06-28 23:12:52      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:mem   pow   +=   复杂度   onclick   const   EDA   color   spl   

整数:求a^n,把n化为2*(k1+k2+..+km); 

矩阵:注意矩阵乘法。

复杂度:O(logn)

tip:取了模(根据题目要求)

技术图片
 1 #include<bits/stdc++.h>
 2 #define mem(a) memset(a,0,sizeof(a))
 3 #define ll long long
 4 using namespace std;
 5 ll mod=1e9;
 6 ll quickpow(ll a,ll n){
 7     ll ans=1;
 8     while(n){
 9         if(n&1)
10             ans=(ans*a)%mod; //取模
11         n>>=1;
12         a=(a*a)%mod;
13     }
14     return  ans%mod;
15 }
16 int main(){
17    cout<<quickpow(2,19);
18    return 0;
19 }
整数
技术图片
 1 #include<bits/stdc++.h>
 2 #define mem(a) memset(a,0,sizeof(a))
 3 #define ll long long
 4 const int N=1e6+5;
 5 using namespace std;
 6 ll mod=1e9;
 7 struct matrix{
 8   int m[N][N];
 9 };
10 matrix mat_multi(matrix a, matrix b){
11    matrix ans;
12    for(int i=0;i<N;i++){
13     for(int j=0;j<N;j++){
14         ans.m[i][j]=0;
15         for(int k=0;k<N;k++){
16             ans.m[i][j]+=(a.m[i][k]%mod*b.m[k][j]%mod)%mod;
17             ans.m[i][j]%=mod;
18         }
19     }
20    }
21    return ans;
22 }
23 matrix quickpow(matrix a,ll n){
24     matrix ans;
25     for(int i=0;i<N;i++){
26         for(int j=0;j<N;j++){
27             if(i==j) ans.m[i][j]=1;
28             else ans.m[i][j]=0; 
29     //初始化为单位矩阵,类比整型时的1;单位矩阵*矩阵A=矩阵A
30         }
31     }
32     while(n!=0){
33         if(n&1)
34             ans=mat_multi(a,ans); 
35         n>>=1;
36         a=mat_multi(a,a);
37     }
38     return  ans;
39 }
矩阵

 

Fast Power

标签:mem   pow   +=   复杂度   onclick   const   EDA   color   spl   

原文地址:https://www.cnblogs.com/XXrll/p/11104978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!