A^X mod P(简单数论 + 思维打表)

一.题目链接:

A^X mod P

二.题目大意:

给出 T,n, A, K,a, b, m, P.

1 \leq n\leq 10^{6}

0 \leq A, K, a, b \leq 10^{9}

1 \leq m, P \leq 10^{9}

T 组样例.

 f(x) = \left\{\begin{matrix}1\;\;\;x=1 & & & & & & & & \\(a \times f(x - 1) + b)\;(mod\;\;m)\;\;\;x > 1 & & & & & & & & \end{matrix}\right.

求 A^{f(1)}+A^{f(2)}+....+A^{f(n)} \;\;(mod\;\;p).

三.分析:

由于 1 \leq m \leq 10^{9}

所以 1 \leq f(x) \leq 10^{9}

如果用快速幂求和的话会 TLE.

因为 A^{f(x)} = A^{a\times 10^{5} + b}

所以只需要求 sum1[] 和 sum2[].

sum1[i]:A^{i}\;\;(mod\;\;p)

sum2[i]:A^{10^{5}i}\;\;(mod\;\;p)

所以 A^{f(x)} = sum1[i \;mod\;M] \times sum2[i\;/\;M]

详见代码.

四.代码实现:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define eps 1e-6
#define PI acos(-1.0)
#define ll long long int
using namespace std;

const int M = (int)1e5;
ll n, A, K, a, b, m, p;
ll sum1[M + 5];
ll sum2[M + 5];

void init()
{
    sum1[0] = sum2[0] = 1;
    for(int i = 1; i <= M; ++i)
        sum1[i] = sum1[i - 1] * A % p;
    sum2[1] = sum1[M];
    for(int i = 1; i <= M / 10; ++i)
        sum2[i] = sum2[i - 1] * sum2[1] % p;
}

ll f()
{
    ll fx = K;
    ll sum = 0;
    for(ll i = 1; i <= n; ++i)
    {
        sum = (sum1[fx % M] * sum2[fx / M] % p + sum) % p;
        fx = (a * fx + b) % m;
    }
    return sum % p;
}

int main()
{

    int T;
    scanf("%d", &T);
    for(int ca = 1; ca <= T; ++ca)
    {
        cin >> n >> A >> K >> a >> b >> m >> p;
        init();
        ll ans = f();
        printf("Case #%d: %lld\n", ca, ans);
    }
    return 0;
}

 

你可能感兴趣的:(#,思维,#,简单数论)