加法快速幂:
int quick_pow(int a,int b)
{
int ans=0;
while(b)
{
if(b&1) ans+=a;
b>>=1;
a+=a;
}
return ans;
}
乘法快速幂:
int quick_pow(int a,int b)
{
int ans=1;
while(b)
{
if(b&1) ans*=a;
b>>=1;
a*=a;
}
return ans;
}
矩阵快速幂;(HDU 1005)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int A,B;
struct Mar //通过结构体构造矩阵更方便
{
int m[2][2];
};
Mar quick_pow1(Mar a,Mar b) //矩阵的乘法
{
Mar tmp;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
tmp.m[i][j]=0;
for(int k=0;k<2;k++)
{
tmp.m[i][j]=(tmp.m[i][j]+(a.m[i][k]*b.m[k][j]))%7;
}
}
}
return tmp;
}
int quick_pow(int n)
{
Mar ans,tmp;//初始化矩阵
tmp.m[1][0]=ans.m[0][0]=ans.m[1][1]=1;
tmp.m[0][0]=ans.m[1][0]=ans.m[0][1]=0;
tmp.m[0][1]=B;tmp.m[1][1]=A;
while(n)
{
if(n&1) ans=quick_pow1(ans,tmp);
n>>=1;
tmp=quick_pow1(tmp,tmp);
}
return (ans.m[0][1]+ans.m[1][1])%7;
}
int main()
{
int n;
while(~scanf("%d %d %d",&A,&B,&n))
{
if(A==0&&B==0&&n==0) break;
int res;
if(n==1||n==2) res=1;
else res=quick_pow(n-2);
printf("%d\n",res);
}
return 0;
}