Iterated Linear Function 矩阵快速幂

Consider a linear function f(x) = Ax + B. Let’s define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values A, B, n and x find the value of g(n)(x) modulo 109 + 7.

Input
The only line contains four integers A, B, n and x (1 ≤ A, B, x ≤ 109, 1 ≤ n ≤ 1018) — the parameters from the problem statement.

Note that the given value n can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

Output
Print the only integer s — the value g(n)(x) modulo 109 + 7.

直接快速幂就行,但是忽然发现自己博客一个矩阵快速幂都没有,,,就推一下;[a,b,0,1]^n* [x,0,1,0]

ll 和 初始化。。。各自WA一发。难受

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define _for(i,a,b) for(int i=(a);i<=(b);i++)
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
ll a, b, n, x;
struct mat {
    ll m[2][2];
};
mat temp = {{1, 0, 0, 1}};
mat muti(mat a, mat b) {
    mat ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(ll i = 0; i < 2; i++) {
        for(ll j = 0; j < 2; j++) {
            ans.m[i][j] = 0;
            for(ll k = 0; k < 2; k++) {
                ans.m[i][j] = (ans.m[i][j] % mod + a.m[i][k] * b.m[k][j] % mod) % mod;
            }
        }
    }
    return ans;
}
mat mquick(ll xxx) {
    mat ans = temp;
    mat temp2 = {{a, b, 0, 1}};
    while(xxx) {
        if(xxx & 1)
            ans = muti(ans, temp2);
        temp2 = muti(temp2, temp2);
        xxx >>= 1;
    }
    return ans;
}
int main() {
    while(~scanf("%lld %lld %lld %lld", &a, &b, &n, &x)) {
        mat fuck = {{x, 0, 1, 0}};
        fuck = muti(mquick(n), fuck);
        printf("%lld\n", (fuck.m[0][0] % mod + mod) % mod);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值