"Recursive" common recursive relationship The topic description considers the following definition of a recursive relationship on a nonnegative integer n:
Where A and B are constants that meet the following two conditions:
Given F0, F1, A, b and N, please write a program that calculates F (n), which can be assumed that f (n) is an integer (rounded) with an absolute value not exceeding 109.
Enter the input file one line to give 5 number, F0, f1,a,b and n,f0,f1 is absolute value not more than 109, n is non-negative integer, not more than 109. In addition, A, B is a real number satisfying the above conditions, and |a|,|b|≤106. Output a row, the value of F (n) sample input
0 1 1) 1 20
Sample output
6765
A simple matrix fast power
Code:
#include <iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<algorithm>#include<climits>#include<cstring>#include<string>#include<Set>#include<map>#include<queue>#include<stack>#include<vector>#include<list>#include<ext/rope>#defineRep (I,m,n) for (i=m;i<=n;i++)#defineRSP (It,s) for (Set<int>::iterator It=s.begin (); It!=s.end (); it++)#defineVI vector<int>#definePII pair<int,int>#defineMoD 1000000007#defineINF 0x3f3f3f3f#definePB Push_back#defineMP Make_pair#defineFi first#defineSe Second#definell Long Long#definePi ACOs (-1.0)Const intmaxn=3e5+Ten;Const intdis[][2]={{0,1},{-1,0},{0,-1},{1,0}};using namespacestd;using namespace__gnu_cxx;ll gcd (ll p,ll q) {returnq==0? P:GCD (q,p%q);} ll Qpow (ll p,ll q) {ll F=1; while(q) {if(q&1) f=f*p;p=p*p;q>>=1;}returnF;}structmat{intn,m,a[2][2]; Mat (intI=0,intj=0) {n=i,m=J; Memset (A,0,sizeof(a)); } Matoperator*(ConstMAT&P)Const{Mat q (n,p.m); inti,j,k; Rep (I,0, N-1) Rep (J,0, M-1) Rep (k,0, p.m-1) Q.a[i][k]= (Q.a[i][k]+1ll*a[i][j]*p.a[j][k])%MoD; returnQ; }};intMain () {inti,j,m,k,t; Mat F (1,2); ll A,b,n,x; scanf ("%lld%lld%lld%lld%lld", &f.a[0][0],&f.a[0][1],&a,&b,&N); Mat g (2,2); g.a[0][0]=0, g.a[0][1]=b,g.a[1][0]=1, g.a[1][1]=A; if(n==0) Exit (0*printf ("%d\n", f.a[0][0])); N--; while(n) {if(n&1) f=f*G; G=g*G; N>>=1; } printf ("%d\n", f.a[0][1]); //System ("pause"); return 0;}
"Recursive" common recursive relationship