Quadratic equation in Prolog

Example for versions gprolog 1.3.0

Conditional branching in Prolog is done via ; and , predicates, which correspond to “or” and “and” logical operations. Evaluation starts with first branch (for example, check for A being 0 in line 3); all predicates separated with , are evaluated in row; if all of them evaluate to true, the whole program evaluates to true as well (and further evaluation stops), otherwise the next branch is evaluated.

read_integer is GNU Prolog extension, other implementations don’t have this predicate built-in.

q :- write('A = '),
     read_integer(A),
     (   A = 0, write('Not a quadratic equation');
         write('B = '),
         read_integer(B),
         write('C = '),
         read_integer(C),
         D is B*B-4*A*C,
         (   D = 0, write('x = '), X is -B/2/A, write(X);
             D > 0, write('x1 = '), X1 is (-B+sqrt(D))/2/A, write(X1), nl, write('x2 = '), X2 is (-B-sqrt(D))/2/A, write(X2);
             R is -B/2/A, I is abs(sqrt(-D)/2/A), 
             write('x1 = ('), write(R), write(', '), write(I), write(')'), nl,
             write('x1 = ('), write(R), write(', -'), write(I), write(')')
         )
     ).

q.