Under construction

Still being built. Things may change

Slon's Expression

Time limit1sMemory limit64 MB

Summary
Parse a linear expression in x and find the smallest non-negative x with the expression congruent to P modulo M.
Level

Medium6 of 10

Topics
Number theory, Math, Stack
Solved
No attempts yet

Problem

Slon is a student who never sits still in class. His teacher wants to keep him quiet, so she gives him a hard arithmetic problem.

The teacher writes an arithmetic expression AA and two integers PP and MM. Slon has to answer this question: what is the smallest non-negative value of the variable xx for which the remainder of AA divided by MM equals PP? An answer always exists.

Expanding AA with the distributive law never produces a term where xx is multiplied by xx. In other words, AA is a polynomial of degree at most one in xx.

The expression can evaluate to a negative number, so the remainder is always defined as the value between 00 and M−1M - 1.

Valid expressions look like 5+x*(3+2) and x+3*x+4*(5+3*(2+x-2*x)). Invalid expressions look like 5*(3+x*(3+x)) and x*(x+x*(1+x)).

Input

The first line contains the expression AA (1≤∣A∣≤100 0001 \le |A| \le 100\,000).

The second line contains two integers PP and MM (0≤P≤M−10 \le P \le M - 1, 1≤M≤1 000 0001 \le M \le 1\,000\,000).

AA consists only of the characters +, -, *, (, ), x and the digits 0 to 9. Brackets are always paired. Every +, - and * is applied to exactly two values, so an expression such as (-5) or (4+-5) never appears. Every multiplication is written out, so an expression such as 4(5) or 2(x) never appears either.

Output

Print the smallest non-negative value of xx that satisfies the condition, on one line.

Note

Take AA = 5+3+x, P=9P = 9 and M=10M = 10. For x=0x = 0 the remainder is 88, and for x=1x = 1 the remainder is 99, so the answer is 11.

Examples3

  1. Example 1

    Input
    5+3+x
    9 10
    
    Expected output
    1
    
  2. Example 2

    Input
    20+3+x
    0 5
    
    Expected output
    2
    
  3. Example 3

    Input
    3*(x+(x+4)*5)
    1 7
    
    Expected output
    1