Educational Codeforces Round 13 D:Iterated Linear Function(数论)

本文探讨了如何解决Codeforces上的一道题:给定线性函数f(x) = Ax + B,定义g(0)(x) = x 和 g(n)(x) = f(g(n-1)(x))。对于给定的A、B、n和x,要求计算g(n)(x) mod 10^9 + 7。文章给出了详细的解析过程及C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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, nand 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.

 
input
3 4 1 1
output
7
input
3 4 2 1
output
25
input
3 4 3 1
output
79

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
const long long MOD = 1000000007;
typedef long long ll;
//逆元 费马小定理
ll pow(ll x,ll y)
{
    ll res=1;
    while(y){
        if(y&1) res=res*x%MOD;
        x=x*x%MOD;
        y>>=1;
    }
    return res;
}

int main()
{
    ll a,b,n,x;
    cin>>a>>b>>n>>x;
    ll res;
    if(a==1){
        res=(x+n%MOD*b)%MOD;
    }
    else{
        res=pow(a,n)*x%MOD;
/*
答案是 pow(A,n) + 一个等比数列
式子可以变成等比数列,然后直接用 Sn = B*a1*(q^n-1)/(q-1) 计算
a1 = 0,q = A
因为每次都要取模,所以要用逆元来算,不能直接除以q-1,而是应该乘以它的乘法逆元
根据费马小定理: 假如MOD是素数,且a与MOD互质,那么a^(MOD-1)=1(mod MOD)
当我们除以 q-1 的时候,我们就是乘以 1/(q-1)
所以 (q-1)^(MOD-1)=1%MOD
两边同乘1/(q-1)得:(q-1)^(MOD-2)=(1-q)%MOD
即是下面的算式
*/
        res+=(pow(a,n)-1)*pow(a-1,MOD-2)%MOD*b;
        res=(res%MOD+MOD)%MOD;
    }
    cout<<res<<endl;
    return 0;
}
 
    

2016-06-15

 
    
 
   

转载于:https://www.cnblogs.com/fightfordream/p/5586359.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值