[tzc3012:Fibnacci Numbers]降幂公式+矩阵快速幂+斐波那契求和公式

来源:互联网 发布:十字绣软件 编辑:程序博客网 时间:2024/04/29 17:07

题目链接:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=3012


Description

The fibnacci numbers are as follows:
f[1] = 1; f[2] = 2;
f[n] = f[n - 1] + f[n - 2];
And s[n] is defined:

Now ,give you the integer number a, x and n, you should calculate the ans, and the ans is defined as follows:
ans = as[x] % n;
You must pay attention to the range of the number: 1 ≤ a ≤ 100000000; 1 ≤ x ≤ 1000000000; 2 ≤ n ≤ 100000000.

Input

The input contains several test cases. For each test case, only line contains three integer numbers a, x and n separated by spaces.
The end of the input is indicated by a line containing three zeros separated by spaces.

Output

For each test case the output is only one integer number ans in a line.

Sample Input

1 1 100
2 3 1000000
0 0 0

Sample Output

1
16384

Source

HNU Monthly 2009.12


解题思路:




1.先用斐波那契前n项平方和公式简化一下表达式;  ans = a^(F(x)*F(x+1) - 1) % n

2.指数比较大,用降幂公式 a ^ b % c =  a^(b%phi(c) + phi(c) ) % c

3.斐波那契的项数比较多(x比较大),F(x)%phi(n)考虑矩阵快速幂取模解决


#include<iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<vector>#include<queue>#include<stack>#include<set>#include<map>#include<algorithm>#include<climits>#include<sstream>#define eps 1e-9#define pi aocs(-1)#define INF 0x3f3f3f3f#define inf -INFusing namespace std;const int maxn = 1e3 + 10;typedef long long LL;LL a,x,n,phi_n,F1,F2;struct matrix{  LL m[2][2];}p,q;LL phi(LL n){  LL res = n;  for(int i = 2;i*i<=n;++ i){    if(n%i==0){        res = res - res/i;        do{            n/=i;        }while(n%i == 0);    }  }  if(n > 1) res = res - res/n;  return res;}matrix multi(matrix a,matrix b,LL mod){  matrix c;  for(int i = 0;i < 2;++ i)  for(int j = 0;j < 2;++ j){    c.m[i][j] = 0;    for(int k = 0;k < 2;++ k)        c.m[i][j]+=a.m[i][k]*b.m[k][j];    c.m[i][j]%=mod;  }  return c;}matrix quick_mod(matrix a,LL b,LL mod){  matrix ans = p;  while(b){    if(b&1) ans = multi(ans,a,mod);    b>>=1;    a = multi(a,a,mod);  }  return ans;}LL quickpow_mod(LL a,LL b,LL mod){  LL res = 1;  while(b){    if(b&1) res = (res*a)%mod;    b>>=1;    a = (a*a)%mod;  }  return res;}void init(){  p.m[0][0] = p.m[1][1] = 1; p.m[1][0] = p.m[0][1] = 0;  q.m[0][0] = q.m[0][1] = q.m[1][0] = 1;q.m[1][1] = 0;}int main(){    matrix ans;    init();    while(cin>>a>>x>>n&&a+x+n){        phi_n = phi(n);        ans = quick_mod(q,x+1,phi_n);        F1 = (ans.m[0][0]*ans.m[0][1]%phi_n + phi_n -1)%phi_n + phi_n;        LL res = quickpow_mod(a,F1,n);        cout<<res<<endl;    }return 0;}


1 0
原创粉丝点击