题目描述:
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 1e9 + 7.
Example
Input
3 4 1 1
Output
7
Input
3 4 2 1
Output
25
Input
3 4 3 1
Output
79
题意:
f(x) = Ax + B
g(0)(x) = x
g(n)(x) = f(g(n - 1)(x))
给了三个式子,求g的n次方模1e9 + 7的结果
解题思路:
只要代入求解就可以得到规律
从第二项起到最后一项,可以将B提出来,那么剩下的就是一个等比数列,可以利用等比数列求和公式。
因为等比数列公式求和有除法,那么取模需要特别注意。
重点内容
加法,减法,乘法取模就不说了,基础。
附AC代码:
# include <cstdio>
using namespace std;
long long mod = 1000000007;
long long quick(long long a,long long b) //快速幂取模
{
long long ans = 1;
long long t = a % mod;
while(b)
{
if(b&1)
{
ans = ans * t % mod;
}
t = t * t % mod;
b >>= 1;
}
return ans;
}
int main()
{
long long A,B,n,x;
long long sum = 0;
scanf("%lld %lld %lld %lld",&A,&B,&n,&x);
if(A == 1)
{
printf("%lld\n",((n%mod*B)%mod+x)%mod); // 当A为 1 不可以取逆元
}
else
{
long long an = quick(A,n)%mod;
sum =(an * (x%mod)) % mod; //计算A的n次方乘x
long long ni = quick(A-1,mod-2); //计算A-1的逆元 ,因为等比数列求和分
// 母是1-A,是负数,所以换一下
sum = (sum % mod + (B%mod * (an-1)%mod * ni %mod) % mod) % mod;
// 计算A的n次方乘x 加上 B *(等比数列求和)
printf("%lld\n",sum);
}
return 0;
}