UPC——2219——A^X mod P

来源:互联网 发布:兰州招聘seo 编辑:程序博客网 时间:2024/05/21 08:52

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

Sample Output

Case #1: 14
Case #2: 63

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int M=100005;long long n,A,K,a,b,m,P;long long ans1[M+1],ans2[M+1];void init(){    ans1[0]=1;    ans2[0]=1;    for(int i=1;i<=M;i++)    {        ans1[i]=ans1[i-1]*A%P;    }    for(int i=1;i<=M;i++)    {        ans2[i]=ans2[i-1]*ans1[M]%P;    }}long long fn(){    long long res=0,t=K;    for(int i=1;i<=n;i++)    {        res=(res+ans2[t/M]*ans1[t%M])%P;        t=(a*t+b)%m;    }    return res;}int main(){    int t;    scanf("%d",&t);    for(int i=1;i<=t;i++)    {        scanf("%lld %lld %lld %lld %lld %lld %lld",&n,&A,&K,&a,&b,&m,&P);        init();        printf("Case #%d: %lld\n",i,fn());     }    return 0;}


0 0