#1641. A^X mod P

    ID: 1641 传统题 25000ms 64MiB 尝试: 0 已通过: 0 难度: (无) 上传者: 标签>2013山东省省赛数论快速幂模运算周期性

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