11的二进制为1011,即11== 2º×1+2¹×1 +2²×0 +2³×1
快速幂:a¹¹= a^1*a^2*a^8
//快速幂
#include<iostream>
using namespace std;
typedef long long ll;
ll pow_quick (ll a,ll b){
ll ans=1,base=a;
while (b!=0)
{
if (b&1==1)//末位为1(否则为0)
ans*=base;
base*=base;
b>>=1;
}
return ans;
}
int main()//计算2^11
{
ll a=2,b=11,ans;
ans=pow_quick(a,b);
cout<<ans<<endl;
}
关于base*=base这一步:因为 base*base==base2,下一步再乘,就是base2*base2==base4,然后同理 base4*base4=base8,由此可以做到base–>base2–>base4–>base8–>base16–>base32…….指数正是 2^i ,再看上面的例子,a¹¹= a1*a2*a8,这三项就可以完美解决。
//快速幂取模
#include<iostream>
using namespace std;
typedef long long ll;
#define mod 1000000007
//对底数和每个乘法取模
ll pow_mod (ll a,ll b){
ll ans=1,base=a;
a%=mod;
while (b!=0)
{
if (b&1==1)
ans=(ans*base)%mod;
base=(base*base)%mod;
b>>=1;
}
return ans%=mod;
}
int main()
{
ll n,m,ans;
cin>>n>>m;
//对底数和每个乘法取模
m%=mod;
//计算m^n−m∗(m−1)^(n−1)
ans=pow_mod(m,n)-(m*pow_mod(m-1,n-1))%mod;
//(结果+mod)然后再取模,否则可能有负值
cout<<(ans+mod)%mod<<endl;
}
附:超大数快速幂。
http://acm.fzu.edu.cn/problem.php?pid=1759
Problem 1759 Super A^B mod C
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,C<=1000000000,1<=B<=10^1000000).
Input
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of A^B mod C.
Sample Input
3 2 4 2 10 1000
Sample Output
1 24
Source
FZU 2009 Summer Training IV–Number Theory
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include<string>
#include<cmath>
using namespace std;
typedef __int64 ll;
int phi(int x)
{
int i,j;
int num = x;
for(i = 2; i*i <= x; i++)
{
if(x % i == 0)
{
num = (num/i)*(i-1);
while(x % i == 0)
{
x = x / i;
}
}
}
if(x != 1) num = (num/x)*(x-1);
return num;
}
ll quickpow(ll m,ll n,ll k)
{
ll ans=1;
while(n)
{
if(n&1) ans=(ans*m)%k;
n=(n>>1);
m=(m*m)%k;
}
return ans;
}
char tb[1000015];
int main()
{
ll a,nb;
int c;
while(scanf("%I64d%s%d",&a,tb,&c)!=EOF)
{
int PHI=phi(c);
ll res=0;
for(int i=0;tb[i];i++)
{
res=(res*10+tb[i]-'0');
if(res>c)break;
}
if(res<=PHI)
{
printf("%I64d\n",quickpow(a,res,c));
}
else
{
res=0;
for(int i=0;tb[i];i++)
{
res=(res*10+tb[i]-'0')%PHI;
}
printf("%I64d\n",quickpow(a,res+PHI,c));
}
}
return 0;
}
别问我,大神的代码,我看不懂。