Iterated Linear Function

有很多种构造方法
我的构造方法是
A 1
0 1

#include 
#define ll long long
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int mod=1e9+7;
struct matrix{
    ll m[2][2];
}ans,bs;
ll m,a,b,x;

matrix multi(matrix a,matrix b){
    matrix c;
    for(ll i = 0; i < 2; i++){
        for(ll j = 0; j< 2; j++){
            c.m[i][j] = 0;
            for(ll k = 0; k< 2; k++){
                c.m[i][j] = (c.m[i][j]+a.m[i][k]*b.m[k][j]%mod)%mod;
            }
        }
    }
    return c;
}

ll fast_mod(ll n){
    bs.m[0][0]=a;
    bs.m[1][1]=bs.m[0][1]=1;
    ans.m[0][0]=ans.m[1][1]=1;
    bs.m[1][0]=ans.m[0][1]=ans.m[1][0]=0;
    while(n){
        if(n&1)
        ans=multi(ans,bs);
        bs=multi(bs,bs);
        n>>=1;
    }
    return (ans.m[0][0]*x%mod+ans.m[0][1]*b%mod)%mod;
}

int main()
{
    while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&m,&x)){
        printf("%I64d\n",fast_mod(m));
    }
    return 0;
}

你可能感兴趣的:(矩阵快速幂)