A^X mod P(山東第四屆省賽)
阿新 • • 發佈:2019-04-10
data- ane lar mce align while overflow 程序 clas
Description
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.
Input
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
Output
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.
Sample
Input
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
Output
Case #1: 14 Case #2: 63
Hint
Source
2013年山東省第四屆ACM大學生程序設計競賽#include <stdio.h> #include <vector> #include <string.h> #include <iostream> #include <algorithm> #include <queue> using namespace std; #define ll long long const int inf = 0xffffff; const int maxn = 1e6+8; int n, t; ll A, K, a, b, m, P, f[maxn], fi[maxn]; ll qsm(ll x, ll y, ll z) { ll ans = 1; while(y) { if(y&1) { ans = ans*x%z; } x = x*x%z; y >>= 1; } return ans; } int main() { scanf("%d", &t); int ga = t; while(t--) { ll sum; scanf("%d%lld%lld%lld%lld%lld%lld", &n, &A, &K, &a, &b, &m, &P); ll miao = K;//存下第一項,f(x) = k sum = qsm(A, K, P);//存下第一項 A^(f(1))%P for(int i = 1; i<n; i++) { miao = (a*miao+b)%m;//由題可知,後一項等於 a*前一項+b,這裏是依次算出以後的每一個f(i) sum = (sum+qsm(A, miao, P))%P;//這裏是依次算出A^(f(i))%P } printf("Case #%d: %lld\n", ga-t, sum); } return 0; }
A^X mod P(山東第四屆省賽)