标签:des style blog color io os sp div 2014
2014-10-02
20:34:27
时间限制: 1 s
输入b,p,k的值,编程计算bp mod k的值。其中的b,p,k*k为长整型数(2^31范围内)。
b p k
输出b^p mod k=?
=左右没有空格
2 10 9
2^10 mod 9=7
赤裸裸的快速幂
a^1=a;
a^b(b为偶数)=a^b/2*a^b/2;
a^b(b为奇数)=a^b/2*a^b/2*a;
所以时间复杂度为O(logn);
1 # include<cstring>
2 # include<cstdio>
3 # include<algorithm>
4 # include<iostream>
5 using namespace std;
6 typedef unsigned long long LL;
7 LL a,b,c;
8 LL mod(LL a,LL b,LL c){
9 LL ans;
10 if(b==1)return a%c;
11 else if(b%2==0) {ans=mod(a,b/2,c);return ans*ans%c;}
12 else if(b%2==1) {ans=mod(a,b/2,c);return ans*ans*a%c;}
13 }
14 int main(){
15 cin>>a>>b>>c;
16 cout<<a<<"^"<<b<<" "<<"mod"<<" "<<c<<"="<<mod(a,b,c)%c;
17 return 0;
18 }//b^p mod k=?
标签:des style blog color io os sp div 2014
原文地址:http://www.cnblogs.com/zoniony/p/4004403.html