CodeForces - 678D Iterated Linear Function

本文探讨了如何通过快速幂和等比数列求和的方法解决迭代线性函数的求值问题。对于给定的线性函数 f(x) = Ax + B 和参数 n, x,文章介绍了计算 g(n)(x) 的值并对 10^9 + 7 取模的算法。


D. Iterated Linear Function
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 ABnand x find the value of g(n)(x) modulo 109 + 7.

Input

The only line contains four integers ABn 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.

Examples
input
3 4 1 1
output
7
input
3 4 2 1
output
25
input
3 4 3 1
output
79
快速幂+等比数列求和  

由于等比数列求和公式需要用到除法,所以取摸运算注意用到逆元。

 ( a/b ) % c == ( a*b1 ) % c;

b1=pow_mod(b,mod-2,mod);

#include<stdio.h>
#include<math.h>
#define mod 1000000007
long long pow_mod(long long a,long long b,long long mod_val)
{
    long long ans=1;
    long long  t=a%mod_val;
    while(b)
    {
        if(b&1)
        {
            ans=ans*t%mod_val;
        }
        t = t*t%mod_val;
        b>>=1;
    }
    return ans;
}

int main()
{
    long long A,B,n,x,b,ans;
    while(scanf("%lld%lld%lld%lld",&A,&B,&n,&x)!=EOF)
    {
        long long a=pow_mod(A,n,mod);
        if(A==1)
        {
            ans=(x+(n%mod*B))%mod;
        }
        else
        {

            b=pow_mod(A-1,mod-2,mod);
            ans=(a-1)%mod;
            ans=ans*b%mod*B%mod;
            ans=(ans+a*x+mod)%mod;
        }
        printf("%lld\n",ans);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值