Contemplation! Algebra
Given the value of a+b and ab you will have to find the value of a
n + b
n
Input
The input file contains several lines of inputs. Each line except the last line contains 3 non-negative
integers p, q and n. Here p denotes the value of a+b and q denotes the value of ab. Input is terminated
by a line containing only two zeroes. This line should not be processed. Each number in the input file
fits in a signed 32-bit integer. There will be no such input so that you have to find the value of 00
.
Output
For each line of input except the last one produce one line of output. This line contains the value of
a
n + b
n. You can always assume that a
n + b
n fits in a signed 64-bit integer.
Sample Input
10 16 2
7 12 3
0 0
Sample Output
68
91
附:debug:
input:
0 0 0
0 0 1
0 0 200000000
1 3 0
999999 999999 0
1 0 200000000
2 0 61
2 1 0
2 1 100
2 1 200000000
0 0 0
0 1 1
0 1 2
0 1 3
0 1 199999999
0 1 200000000
0 1 200000001
0 1 200000002
5 6 7
10 20 10
90 87 3
999 231 2
0 0
output:
2 0 0 2 2 1 2305843009213693952 2 2 2 2 0 -2 0 0 2 0 -2 2315 393600000 705510 997539 题意:输入p,q,n;p=a+b,q=a*b,输出a^n+b^nTIP:令f(n)=a^n+b^n;则f(n)*(a+b)=a^(n+1)+b^(n+1)+a*b^n+b*a^n =f(n+1)+a*b*f(n-1) 即:f(n+1)=-(a+b)*f(n)+a*b*f(n-1)好了,矩阵上场,对于形如f(n+1)=p*f(n)+q*f(n-1)的;都可以转换为(p,q) (1,0)…………%…………这是个2*2的矩阵
然后{f(n),f(n-1)}……(此为1*2的矩阵)=(那个矩阵)^(n-2)*{f(2),f(1)};
注意:如果输入0,0,2;你的程序运行不?
scanf(……………………==3),我的如果不写的话就超时。
代码:
1 ///a^(n+1)+b^(n+1)=(a^n+b^n)p−(a^(n−1)+b^(n−1)) 2 #include<string.h> 3 #include<stdio.h> 4 5 long long p,q,n; 6 7 struct mat 8 { 9 long long v[2][2]; 10 mat(){memset(v,0,sizeof(v));} 11 mat operator * (mat c) 12 { 13 mat ans; 14 for(int i=0;i<2;i++)///矩阵乘法再加上原有的原数 15 { 16 for(int j=0;j<2;j++) 17 { 18 for(int k=0;k<2;k++) 19 { 20 ans.v[i][j]=ans.v[i][j]+v[i][k]*c.v[k][j]; 21 } 22 } 23 } 24 return ans; 25 } 26 }; 27 28 mat pow_mod(mat x,long long k) 29 { 30 mat ans; 31 ans.v[0][0]=ans.v[1][1]=1; 32 33 while(k)///二分求定以后的* 34 { 35 if(k&1) 36 ans=ans*x; 37 x=x*x; 38 k>>=1; 39 } 40 41 return ans; 42 } 43 44 long long solve() 45 { 46 if(n==0) 47 return 2; 48 if(n==1) 49 return p; 50 if(n==2) 51 return p*p-2*q; 52 53 mat a; 54 a.v[0][0]=p; 55 a.v[0][1]=-q; 56 a.v[1][0]=1; 57 a=pow_mod(a,n-2); 58 59 return a.v[0][1]*p+a.v[0][0]*(p*p-2*q); 60 } 61 62 int main() 63 { 64 while(scanf("%lld%lld%lld",&p,&q,&n)==3) 65 { 66 printf("%lld\n",solve()); 67 } 68 return 0; 69 }