Slon's Expression
Time limit1sMemory limit64 MB
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 and two integers and . Slon has to answer this question: what is the smallest non-negative value of the variable for which the remainder of divided by equals ? An answer always exists.
Expanding with the distributive law never produces a term where is multiplied by . In other words, is a polynomial of degree at most one in .
The expression can evaluate to a negative number, so the remainder is always defined as the value between and .
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 ().
The second line contains two integers and (, ).
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 that satisfies the condition, on one line.
Note
Take = 5+3+x, and . For the remainder is , and for the remainder is , so the answer is .