#1987. A^X mod P

A^X mod P

说明

本题为2013年山东省省赛PROBLEM C

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.

2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
Case #1: 14
Case #2: 63

Source

2013山东省省赛