问题 C: A^X mod P

问题 C: A^X mod P
时间限制: 5 Sec 内存限制: 128 MB

题目描述
It’s easy for ACMer to calculate A^X mod P. Now given seven integers n, A, K, a, b, m, P, and a function f(x) which defined as following.
f(x) = K, x = 1
f(x) = (a*f(x-1) + b)%m , x > 1

Now, Your task is to calculate
( A^(f(1)) + A^(f(2)) + A^(f(3)) + … + A^(f(n)) ) modular P.
输入
In the first line there is an integer T (1 < T <= 40), which indicates the number of test cases, and then T test cases follow. A test case contains seven integers n, A, K, a, b, m, P in one line.
1 <= n <= 10^6
0 <= A, K, a, b <= 10^9
1 <= m, P <= 10^9
输出
For each case, the output format is “Case #c: ans”.
c is the case number start from 1.
ans is the answer of this problem.
样例输入 Copy
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
样例输出 Copy
Case #1: 14
Case #2: 63

本体做法:大幂分解求法
就像9 = 2 * 4 + 1一样,任何一个很大的数T可以写成T = a * N + b;
其中,N为一个任意的比较大的数
这题就是依靠的这样的一个思想。

// 大幂分解求和
#include <iostream>

using namespace std;

typedef long long ll;

const int N = 1e6 + 10;

int t, cnt;
ll s1[N], s2[N];

int main(){
    scanf("%d", &t);
    
    while (t -- ){
        cnt ++;
        int n, A, k, a, b, m, p;
        scanf("%d%d%d%d%d%d%d", &n, &A, &k, &a, &b, &m, &p);
        
        s1[0] = s2[0] = 1;
        for (int i = 1; i < N; i ++ ) s1[i] = s1[i - 1] * A % p;//余数部分`b`
        
        ll v = s1[N - 1];//N为这里的v
        for (int i = 1; i < N; i ++ ) s2[i] = s2[i - 1] * v % p;//整除部分`a`
        
        ll f = k, res = 0;
        for (int i = 1; i <= n; i ++ ){
            res = (res % p + s2[f / (N - 1)] % p * s1[f % (N - 1)] % p) % p;
            f = (a * f % m + b) % m;
        }
        
        printf("Case #%d: %lld\n", cnt, res);
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值