PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000324. Tổng cấp số nhân (Geometric Progression)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổng cấp số nhân (Geometric Progression)

Geometric Progression

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Given positive integers A,X,MA,X,M, consider the sum of the first XX powers of AA:

S=1+A+A2+⋯+AX−1=∑i=0X−1Ai.S=1+A+A^2+\cdots+A^{X-1}=\sum_{i=0}^{X-1}A^i.

Compute the non-negative remainder of SS modulo MM. The modulus MM is not necessarily prime, so modular division by A−1A-1 may be invalid.

Input

One line contains three positive integers A,X,MA,X,M.

Output

Print the integer rr satisfying 0≤r<M0\le r<M and r≡S(modM)r\equiv S\pmod M.

Subtasks

  • Subtask 1 (20 points): 1≤A,M≤1001\le A,M\le100; 1≤X≤1001\le X\le100.
  • Subtask 2 (30 points): 1≤A,M≤1051\le A,M\le10^5; 1≤X≤1061\le X\le10^6.
  • Subtask 3 (50 points): 1≤A,M≤1091\le A,M\le10^9; 1≤X≤10121\le X\le10^{12}.

Examples

Example 1

Input

3 4 7

Output

5

Explanation

The sum is 1+3+9+27=401+3+9+27=40, and 40 mod 7=540\bmod7=5.

Example 2

Input

8 10 9

Output

0

Explanation

Modulo 99, we have 8≡−18\equiv-1. The ten terms form five pairs, each summing to 0 mod 90\bmod9.

Example 3

Input

1000000000 1000000000000 998244353

Output

919667211

Explanation

The exponent X=1012X=10^{12} is too large for term-by-term summation. Repeatedly doubling block lengths gives the remainder 919667211919667211.