Solving Linear Equations
InterviewTime limit1sMemory limit128 MB
Parse each linear equation written in a recursive grammar with parentheses and multiplication, then report no, infinite, or the unique solution rounded to six decimals.
- Level
Medium5 of 10
- Topics
- Math, Recursion, Implementation, String matching
- Solved
- No attempts yet
Problem
You are given linear equations in a single unknown. Write a program that finds the solution of each equation.
Input
The input consists of several equations, one per line.
Every equation is at most 100 characters long and follows the EBNF grammar below.
Equation := Expression '=' Expression
Expression := Term { ('+' | '-') Term }
Term := Factor { '*' Factor }
Factor := Number | 'x' | '(' Expression ')'
Number := Digit | Digit Number
Digit := '0' | '1' | ... | '9'
This grammar can also produce non-linear expressions such as x*x = 25, but the input always gives an equation that is linear in x. Moreover, every sub-expression of an equation is also linear, so an expression such as x*x - x*x + x = 0 (where x*x is not linear) is never given.
Every number that appears in the input is a non-negative integer, and x is a real number.
Output
For each test case, first print Equation #i, where i is the test case number (starting from 1). On the next line, print exactly one of the following.
- If the equation has no solution, print
No solution. - If the equation has infinitely many solutions, print
Infinitely many solutions. - If the equation has a unique solution, print
x = solution, wheresolutionis printed with six digits after the decimal point.
Print one blank line between consecutive test cases.