Beautiful Summation

Time limit: 2000 ms
Memory limit: 256 MB

Andy loves arithmetic and geometric progressions. He has mastered the summation formulas for arithmetic and geometric progressions. But, he is already bored with those standard formulas. So, he comes up with a more beautiful summation, i.e.


SN=k=1NPk×kQ S_N= \sum_{k = 1}^{N} P^k \times k^Q


But, he does not know how to calculate the value of SNS_N. Since you are an awesome problem solver, Andy asks your help to calculate the value of SNS_N modulo MM for given numbers PP, QQ, NN, and MM.


Standard input

There is only one line in the input containing four integers separated by single spaces, PP, QQ, NN, and MM that represent the parameters in Andy's summation.


Standard output

You should output an integer between 00 and M1M-1 representing the result of Andy's summation after modulo by MM.


Constraints and notes

  • 1P10001 \leq P \leq 1\,000
  • 0Q10000 \leq Q \leq 1\,000
  • 1N,M1091 \leq N, M \leq 10^9

  • For 20%20\% of the test files, N106N \leq 10^6.
  • For another 40%40\% of the test files (not including the 20%20\% above), M106M \leq 10^6.

InputOutputExplanation
2 3 4 10
4

S4=k=142k×k3 S_4 = \sum_{k=1}^{4} 2^k \times k^3

S4=21×13+22×23+23×33+24×43 S_4 = 2^1 \times 1^3 + 2^2 \times 2^3 + 2^3 \times 3^3 + 2^4 \times 4^3

S4=2+32+216+1024 S_4 = 2 + 32 + 216 + 1024

S4=1274 S_4 = 1274

So, S4mod10=4S_4 \mod 10 = 4

7 0 5 128
23

S5=k=157k×k0 S_5 = \sum_{k=1}^{5} 7^k \times k^0

S5=71×10+72×20+73×30+74×40+75×50 S_5 = 7^1 \times 1^0 + 7^2 \times 2^0 + 7^3 \times 3^0 + 7^4 \times 4^0 + 7^5 \times 5^0

S5=7+49+343+2401+16807 S_5 = 7 + 49 + 343 + 2401 + 16807

S5=19607 S_5 = 19607

So, S5mod128=23S_5 \mod 128 = 23.

Authenticate to use the workspace

Log In
Sign Up
Forgot Password?
or connect with