This page is still under construction.

Parts of this page are still being built. What you see may change.

Solving Linear Equations

Interview

Time limit1sMemory limit128 MB

Summary
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, where solution is printed with six digits after the decimal point.

Print one blank line between consecutive test cases.

Examples1

  1. Example 1

    Input
    x+x+x=10
    4*x+2=19
    3*x=3*x+1+2+3
    (42-6*7)*x=2*5-10
    
    Expected output
    Equation #1
    x = 3.333333
    
    Equation #2
    x = 4.250000
    
    Equation #3
    No solution.
    
    Equation #4
    Infinitely many solutions.