CodeForces - 678D Iterated Linear Function

本文探讨了如何高效计算迭代线性函数 g(n)(x) = f(g(n-1)(x)) 的值,并给出了一种取模运算下的解决方法。特别地,针对 a^n 和 (1-a^n)/(1-a) 的计算提供了具体实现,使用快速幂和乘法逆元等技巧。

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

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 A,Bn and 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 longinteger 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


题意:

fx=ax+b

g0=x

gn=f(gn-1)+b=a*(gn-1)+b

求gn

思路:

通过递推关系可以得到

a=1时 gn=x+b*n

否则  gn=a^n*x+b*(1-a^n)/(1-a)

取余的运算对加减法和乘法满足分配率,但对除法不满足,如果式子中存在除法并且要对式子取余,需要将除法用乘法逆元转化为乘法

求 a / b %c

如果c是素数,则原式= a * b^c-2 % c

如果c不是素数,需要用扩展欧几里得求逆元


#include <iostream>
#include <cstdio>
#include <algorithm>
#define ll long long
#define mod 1000000007
using namespace std;
ll fpow(ll a,ll b)
{
	ll ans=1;
	ll tmp=(a%mod);
	while(b)
	{
		if(b&1)
		ans=(ans*tmp)%mod;
		b/=2;
		tmp=(tmp*tmp)%mod;
	}
	return (ans%mod);
}
int main()
{
	ll a,b,n,x;
	cin>>a>>b>>n>>x;
	if(n==0)
	{
		printf("%lld\n",x%mod);
		return 0;
	}
	if(a==1)
	{
		printf("%lld\n",(x%mod+(b%mod*(n%mod))%mod)%mod);
		return 0;
	}
	ll d=fpow(a,n);
	ll ans=(d*x%mod+b%mod*(1-d)%mod*fpow(1-a,mod-2)%mod)%mod;
	printf("%lld\n",ans);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值