Skip to main content
LIVE CONTEST: ALGOR Contest: Round #4 (Special Challenge) is live now!

~/algor $ cat problems/sonlar-daraja-darajasi

Remainder of a power tower

Medium 1000 ms 128 MB 51%
Share

You are given positive integers $a$, $b$, a non-negative integer $c$ and a prime $p$. Find the remainder of $a^{\left(b^{c}\right)}$ divided by $p$. For example, for $a = 2$, $b = 3$, $c = 2$ we get $2^{9} = 512$, and its remainder modulo $13$ is $5$.

The remainders of the powers of a modulo p; they repeat after p − 1 steps

Input

One line with four integers: $a$, $b$, $c$ and $p$.

Output

One integer — the remainder.

Note

$1 \le a, b \le 10^{9}$
$0 \le c \le 10^{9}$
$2 \le p \le 10^{9} + 7$, $p$ is prime

Examples

Input #1
2 3 2 13
Output #1
5
Input #2
5 1 0 7
Output #2
5

Sign in to submit a solution

Signing up is free and takes a minute.