Quadratic equation
A quadratic equation is an equation of form Ax2 + Bx + C = 0, where A, B and C are given constants (with a constraint A != 0).
To solve it, a discriminant is calculated: D = B2-4AC. If D = 0, the equation has one real root x = -B/2A, otherwise it has two roots x1 = (-B+sqrt(D))/2A, x2 = (-B-sqrt(D))/2A (the roots are real or complex, depending on whether D is positive or negative).
The task is to read integer constants A, B and C entered by user, calculate the roots of the equation and output them. If A = 0, output an error message “Not a quadratic equation”. Output real roots as a single double, and complex roots a + ib as (a,b).
This class of examples shows processing of floating-point and complex numbers (if the language provides these data types). Besides, both console and graphical user interface can be used for interacting with the user.
Example for versions Borland C++ Builder 6
This example uses a template class complex<>, provided in STL. All calculations are done in complex numbers, because this allows not to worry about the sign of discriminant and representation of the roots.
Operator >> of complex is overloaded so that it can recognize several formats of the number, so the input constants are read not as integers but as complex numbers without imaginary part. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point and even complex ones.
Operator << is also overloaded to print the number x as (x.real(),x.imag()), so to print roots without imaginary part as a single double, function print was created.
#include <iostream>
#include <complex>
#include <math>
using namespace std;
void print(int ind, complex<double> x)
{ cout << "x" << ind << " = ";
if (fabs(x.imag()) < 1E-6)
cout << x.real() << endl;
else cout << x << endl;
}
void main()
{ complex<double> A, B, C, D, x1, x2;
cout << "A = ";
cin >> A;
if (abs(A)<1E-3)
{ cout << "Not a quadratic equation" << endl;
return;
}
cout << "B = ";
cin >> B;
cout << "C = ";
cin >> C;
A *= 2;
D = B*B-A*C*2.0;
if (abs(D)<1E-3)
cout << "x = " << (-B/A).real();
else
{ print(1, (-B+sqrt(D))/A);
print(2, (-B-sqrt(D))/A);
}
}
Example for versions Algol68g-1.18.0
A direct translation of the C++ example.
PROC print root = (INT ind, LONG COMPL x)VOID:
( print(("x", ind, " := "));
IF ABS(im OF x) < 1E-6 THEN
print((re OF x, new line))
ELSE print((x, new line))
FI
);
main:
( LONG COMPL a, b, c, d, x1, x2;
print(("a := "));
read((a));
IF ABS a <1E-3 THEN
print(( "Not a quadratic equation", new line));
stop
FI;
print(("b := "));
read((b));
print(("c := "));
read((c));
a *:= 2;
d := b*b-a*c*2.0;
IF ABS d <1E-3 THEN
print(("x := ", re OF (-b/a)))
ELSE
print root(1, (-b+long complex sqrt(d))/a);
print root(2, (-b-long complex sqrt(d))/a)
FI
)
Example for versions SpiderMonkey (Firefox 3.5)
The example is meant to be executed from the web-browser. To run the example, copy the code to a file quadratic.js and create an HTML file placed in the same directory and containing the following text:
<head>
<script type="text/javascript" src="1.js"></script>
</head>
<body>
<form name="quadratic">
<input type="number" required="required" name="A">
<input type="number" required="required" name="B">
<input type="number" required="required" name="C">
<input type="button" value="Solve" onClick="solve()">
</form>
<p id="output">
</p>
</body>
This will create a web-page with three input fields and a button. The equation will be solved once the button is pressed, and the roots will be printed beneath the inputs.
JavaScript doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.
function print(real, imag)
{ if (Math.abs(imag)<1E-6)
return real;
else
return '('+real+','+imag+')';
}
function solve()
{ A = document.quadratic.A.value;
if (Math.abs(A)<1E-3)
{ document.getElementById('output').innerHTML = 'Not a quadratic equation';
return;
}
B = document.quadratic.B.value;
C = document.quadratic.C.value;
A = 2*A;
D = B*B-2*A*C;
if (Math.abs(D)<1E-3)
{ document.getElementById('output').innerHTML = 'x = '+(-B/A);
return;
}
if (D>0)
document.getElementById('output').innerHTML = 'x1 = '+print((-B+Math.sqrt(D))/A, 0)+'<br />x2 = '+print((-B-Math.sqrt(D))/A, 0);
else
document.getElementById('output').innerHTML = 'x1 = '+print(-B/A,Math.sqrt(-D)/A)+'<br />x2 = '+print(-B/A,-Math.sqrt(-D)/A);
}
Example for versions Sanscript 2.2
Sanscript is a fully visual programming language, so no source code is available. See screeshots instead.
This example contains a lot of branches on condition, and in Sanscript each branch is described in a new flowgram.
Quadratic equation example in Sanscript (main flowgram)
Quadratic equation example in Sanscript (on condition A=0)
Quadratic equation example in Sanscript (on condition A=default)
Quadratic equation example in Sanscript (on condition D=0)
Quadratic equation example in Sanscript (on condition D=default)
Quadratic equation example in Sanscript (on condition D>0)
Quadratic equation example in Sanscript (on condition D<0)
Example for versions gcj 3.4.5, Sun Java 6
Java doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.
The coefficients are read from stream System.in, which allows only individual bytes to be read directly, so two wrapper classes InputStreamReader and BufferedReader are used to make reading more comfortable. The strings read from System.in are converted into double values using parseDouble method of class Double. In Java all input operations must be wrapped in try ... catch blocks to handle IOException — class of exceptions which are thrown by reading routines.
import java.util.*;
import java.io.*;
public class Quadratic {
static String print(double real, double imag)
{ if (Math.abs(imag)<1E-6)
return ""+real;
else
return "("+real+","+imag+")";
}
public static void main(String[] args)
{ double A,B,C,D;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("A = ");
A = Double.parseDouble(br.readLine());
if (Math.abs(A)<1E-3)
{ System.out.println("Not a quadratic equation.");
return;
}
System.out.print("B = ");
B = Double.parseDouble(br.readLine());
System.out.print("C = ");
C = Double.parseDouble(br.readLine());
}
catch (Exception e) {
System.err.println("An error occured while reading input parameters.");
return;
}
A = 2*A;
D = B*B-2*A*C;
if (Math.abs(D)<1E-3)
{ System.out.println("x = "+(-B/A));
return;
}
if (D>0)
System.out.println("x1 = "+print((-B+Math.sqrt(D))/A, 0)+"\nx2 = "+print((-B-Math.sqrt(D))/A, 0));
else
System.out.println("x1 = "+print(-B/A,Math.sqrt(-D)/A)+"\nx2 = "+print(-B/A,-Math.sqrt(-D)/A));
}
}
Example for versions Oracle 10g SQL
This example was tested in SQL*Plus and TOAD.
Pure SQL allows to input values at runtime in the form of substitution variables. To define a substitution variable, use its name (in this case A, B and C) with an ampersand & before it each time you need to reference it. When the query needs to be executed, you will receive a prompt to enter the values of the variables. Each reference to such variable will be replaced with its value, and the resulting query will be executed.
There are several ways to input the values for substitution variables. In this example first reference to each variable has double ampersand && before its name. This way the value of the variable has to be entered only once, and all following references will be replaced with the same value (using single ampersand in SQL*Plus asks to enter the value for each reference to the same variable). Note that the references are substituted with the values “as is”, so negative values of coefficients have to be entered in brackets.
First line of the example sets the character for decimal separator which is used when the numbers are converted into strings.
The query itself is composed of four different queries. Each query returns a string containing the result of calculations for one case of quadratic equation, and returns nothing for three other cases. The results of each query are united to produce the final result.
alter session set NLS_NUMERIC_CHARACTERS='. ';
select 'Not a quadratic equation.' ans
from dual
where &&A = 0
union
select 'x = ' || to_char(-&&B/2/&A)
from dual
where &A != 0 and &B*&B-4*&A*&&C = 0
union
select 'x1 = ' || to_char((-&B+sqrt(&B*&B-4*&A*&C))/2/&A) || ', x2 = ' || to_char(-&B-sqrt(&B*&B-4*&A*&C))/2/&A
from dual
where &A != 0 and &B*&B-4*&A*&C > 0
union
select 'x1 = (' || to_char(-&B/2/&A) || ',' || to_char(sqrt(-&B*&B+4*&A*&C)/2/&A) || '), ' ||
'x2 = (' || to_char(-&B/2/&A) || ',' || to_char(-sqrt(-&B*&B+4*&A*&C)/2/&A) || ')'
from dual
where &A != 0 and &B*&B-4*&A*&C < 0;
Example for versions clisp 2.47, Corman Common Lisp 3.0, gcl 2.6.6
Common Lisp provides complex numbers as datatype, printed as #C(real imag). write-to-string converts a number into a string.
Note that for interactive evaluation it’s enough to add (quadratic-roots-2 1 0 1) to see the result of calculation, while for compiled execution you’ll have to wrap call of this function in printing command, like (format t (quadratic-roots-2 1 0 1)).
(defun quadratic-roots-2 (A B C)
(cond ((= A 0) (string "Not a quadratic equation."))
(t
(let ((D (- (* B B) (* 4 A C))))
(cond ((= D 0) (concatenate 'string "x = " (write-to-string (/ (+ (- B) (sqrt D)) (* 2 A)))))
(t
(values (concatenate 'string "x1 = " (write-to-string (/ (+ (- B) (sqrt D)) (* 2 A))))
(concatenate 'string "x2 = " (write-to-string (/ (- (- B) (sqrt D)) (* 2 A)))))))))))
Example for versions gnat 3.4.5, gnat 4.3.2
Ada provides complex datatype, which requires using packages Generic_Complex_Types and Generic_Complex_Elementary_Functions and instantiating them with the type of complex number to use (in this case — floating-point numbers). Ada doesn’t support implicit data type conversions, so all casts are done explicitly.
with Ada.Text_IO,
Ada.Integer_Text_IO,
Ada.Float_Text_IO,
Ada.Numerics.Elementary_Functions,
Ada.Text_IO.Complex_IO,
Ada.Numerics.Generic_Complex_Types,
Ada.Numerics.Generic_Complex_Elementary_Functions;
use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Float_Text_IO;
procedure QuadraticEquation is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Float);
package Complex_Functions is new Ada.Numerics.Generic_Complex_Elementary_Functions(Complex_Types);
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_Types, Complex_Functions, Complex_IO;
A,B,C,D: Integer;
A2f, Bf, S: Float;
Dc: Complex;
begin
Put("A = ");
Get(Item => A);
if A = 0 then
Put_Line("Not a quadratic equation.");
return;
end if;
Put("B = ");
Get(B);
Put("C = ");
Get(C);
A2f := Float(2*A);
Bf := Float(B);
D := B*B-4*A*C;
if D = 0 then
Put("x = ");
Put(-Bf/A2f);
elsif D > 0 then
S := Ada.Numerics.Elementary_Functions.Sqrt(Float(D));
Put("x1 = ");
Put((-Bf+S)/A2f);
Put_Line("");
Put("x2 = ");
Put((-Bf-S)/A2f);
else
Dc := Compose_From_Cartesian (Re => Float(D), Im => 0.0);
Put("x1 = ");
Put((-Bf+Complex_Functions.Sqrt(Dc))/A2f);
Put_Line("");
Put("x2 = ");
Put((-Bf-Complex_Functions.Sqrt(Dc))/A2f);
end if;
end QuadraticEquation;
Example for versions GHC 6.10.4
Haskell provides complex datatype. Function quadratic accepts a list of complex numbers and returns a list of equation roots. Notation root sign allows to generalize the notation of roots for two signs of square root.
module Main where
import Data.Complex
import System.IO (hFlush, stdout)
quadratic :: (Complex Double, Complex Double, Complex Double) -> [Complex Double]
quadratic (0, _, _) = []
quadratic (a, b, c)
| d == 0 = [root (+)]
| otherwise = [root (+), root (-)]
where d = b*b - 4*a*c
root sign = sign (-b) (sqrt d) / (2*a)
main = do
putStr "A = "
hFlush stdout
a <- readLn :: IO Double
putStr "B = "
hFlush stdout
b <- readLn :: IO Double
putStr "C = "
hFlush stdout
c <- readLn :: IO Double
print $ quadratic (realToFrac a, realToFrac b, realToFrac c)
Example for versions Scratch 1.4
Scratch is a graphical language, the print-screen contains the actual information about the program, source text is only a transcription. This example features the usage of text input in Scratch, which is done with command ask "..." and wait. This command makes the sprite “say” the associated message (used as prompt) and displays an input window below the sprite. Once the information is entered, is can be accessed through predefined variable answer, which is copied to local variables before entering next values.
ask "A = ?" and wait
set A to answer
if A = 0
say "Not a quadratic equation"
else
ask "B = ?" and wait
set B to answer
ask "C = ?" and wait
set C to answer
set D to B*B + (-4)*A*C
set re to B/(-2*A)
if D = 0
say join ("x = " re)
else
set im to (sqrt of (abs of D)) / (2*A)
if D > 0
say join (join ("x1 = " (re+im)) join (", x2 = " (re-im)))
else
say join (join ("x1 = (" join (re join (", " im))) join ("), x2 = (" join (re join (", -" join (im ")")))))
Quadratic equation example in Scratch
Example for versions UCBLogo 6.0
This example defines function quadraticwhich accepts coefficients of quadratic equation and prints the roots. Usage is quadratic 1 -2 1.
to quadratic :A :B :C
if :A = 0 [(print [Not a quadratic equation.])
stop
]
make "D :B*:B - 4*:A*:C
if :D = 0 [(print [x = ] -:B/2/:A)
stop
]
if :D > 0 [(print [x1 = ] (-:B+sqrt :D)/2/:A)
(print [x2 = ] (-:B-sqrt :D)/2/:A)
stop
]
(print [x1 = (] -:B/2/:A [,] (sqrt (-:D))/2/A [)])
(print [x2 = (] -:B/2/:A [,] (-sqrt (-:D))/2/A [)])
end
Example for versions Visual Prolog 7.2
Create a new project with UI Strategy “Console” and replace contents of files main.cl and main.pro with given code.
In main.cl the only added line q : () procedure(). specifies that q is a predicate which doesn’t accept parameters. Keyword procedure describes the behavior of predicate, indicating that is will always succeed with only one solution, so no backtracking is required.
In main.pro the actual description of newly specified predicate takes place. q takes no arguments, since it reads everything it needs from stdio. Conditional evaluation (construct if-then-else) works much like in other languages, with the difference of ! sign before then clause. This is a cut, meaning that once the condition is satisfied, no backtracking is needed.
The tricky part about this example is that we can’t calculate discriminant like in other examples. Default data type for D in assignment D = B*B-4*A*C is uReal, which is unsigned and can’t hold negative values.
% main.cl
class main
open core
predicates
classInfo : core::classInfo.
q : () procedure().
predicates
run : core::runnable.
end class main
% main.pro
implement main
open core
constants
className = "main".
classVersion = "".
clauses
classInfo(className, classVersion).
q() :-
stdio::write("A = "),
A = stdio::read(),
if (A = 0), ! then
stdio::write("Not a quadratic equation."), stdio::nl
else
stdio::write("B = "),
B = stdio::read(),
stdio::write("C = "),
C = stdio::read(),
if (B*B = 4*A*C), ! then
stdio::writef("x = %f", -B/2.0/A)
elseif (B*B > 4*A*C), ! then
D = B*B-4*A*C,
stdio::writef("x1 = %f\n", (-B+math::sqrt(D))/2.0/A),
stdio::writef("x2 = %f", (-B-math::sqrt(D))/2.0/A)
else
D = -B*B+4*A*C,
stdio::writef("x1 = (%f, %f)\n", -B/2.0/A, math::sqrt(D)/2.0/A),
stdio::writef("x2 = (%f, %f)", -B/2.0/A, -math::sqrt(D)/2.0/A)
end if
end if.
clauses
run():-
console::init(),
q(),
succeed().
end implement main
goal
mainExe::run(main::run).
Example for versions Free Pascal 2.0.4, Free Pascal 2.2.0, gpc 20070904, Turbo Pascal 1.0, Turbo Pascal 2.0, Turbo Pascal 3.0, Turbo Pascal 4.0, Turbo Pascal 5.0, Turbo Pascal 6.0
Pascal itself doesn’t have built-in complex data type, so calculations are done in real numbers. Library function halt exits current block (in later versions it is replaced with exit).
program Quadratic;
var
A,B,C,D: integer;
begin
write('A = ');
readln(A);
if (A=0) then
begin
writeln('Not a quadratic equation.');
halt;
end;
write('B = ');
readln(B);
write('C = ');
readln(C);
D := B*B-4*A*C;
if (D=0) then
begin
writeln('x = ',-B/2.0/A);
halt;
end;
if (D>0) then
begin
writeln('x1 = ',(-B+Sqrt(D))/2.0/A);
writeln('x2 = ',(-B-Sqrt(D))/2.0/A);
end
else
begin
writeln('x1 = (',-B/2.0/A,',',Sqrt(-D)/2.0/A,')');
writeln('x2 = (',-B/2.0/A,',',-Sqrt(-D)/2.0/A,')');
end;
end.
Example for versions QuickBASIC 4.5
PRINT "A = "
INPUT A
IF (A = 0) THEN
PRINT "Not a quadratic equation."
ELSE
PRINT "B = "
INPUT B
PRINT "C = "
INPUT C
D = B * B - 4 * A * C
IF (D = 0) THEN
PRINT "x = " + STR$(-B / 2! / A)
ELSE
IF (D > 0) THEN
PRINT "x1 = " + STR$((-B + SQR(D)) / 2! / A)
PRINT "x2 = " + STR$((-B - SQR(D)) / 2! / A)
ELSE
PRINT "x1 = (" + STR$(-B / 2! / A) + "," + STR$(SQR(-D) / 2! / A) + ")"
PRINT "x2 = (" + STR$(-B / 2! / A) + "," + STR$(-SQR(-D) / 2! / A) + ")"
END IF
END IF
END IF
Example for versions gmcs 2.0.1, Microsoft Visual C# 2008
using System;
class Program
{
static void Main(string[] args)
{
int A, B, C, D;
try
{ Console.Write("A = ");
A = Convert.ToInt32(Console.ReadLine());
Console.Write("B = ");
B = Convert.ToInt32(Console.ReadLine());
Console.Write("C = ");
C = Convert.ToInt32(Console.ReadLine());
}
catch
{ Console.WriteLine("Invalid input");
return;
}
if (A == 0)
{ Console.WriteLine("Not a quadratic equation.");
return;
}
D = B * B - 4 * A * C;
if (D == 0)
Console.WriteLine("x = {0}", -B / 2.0 / A);
else if (D > 0)
Console.WriteLine("x1 = {0}\nx2 = {1}", (-B + Math.Sqrt(D)) / 2 / A, (-B - Math.Sqrt(D)) / 2 / A);
else
Console.WriteLine("x1 = ({0},{1})\nx2 = ({0},-{1})", -B/2.0/A, Math.Sqrt(-D)/2/A);
}
}
Example for versions Microsoft Visual Basic .NET 9 (2008)
Module Module1
Sub Main()
Dim A, B, C, D As Integer
Dim p1, p2 As Double
Try
Console.Write("A = ")
A = Val(Console.ReadLine())
Console.Write("B = ")
B = Val(Console.ReadLine())
Console.Write("C = ")
C = Val(Console.ReadLine())
Catch ex As Exception
Console.WriteLine("Invalid input.")
Return
End Try
If A = 0 Then
Console.WriteLine("Not a quadratic equation.")
Return
End If
D = B * B - 4 * A * C
p1 = -B / 2.0 / A
p2 = Math.Sqrt(Math.Abs(D)) / 2.0 / A
If D = 0 Then
Console.Write("x = " & p1.ToString())
ElseIf D > 0 Then
Console.WriteLine("x1 = " & (p1 + p2).ToString())
Console.WriteLine("x2 = " & (p1 - p2).ToString())
Else
Console.WriteLine("x1 = (" & p1.ToString() & "," & p2.ToString() & ")")
Console.WriteLine("x2 = (" & p1.ToString() & ",-" & p2.ToString() & ")")
End If
End Sub
End Module
Example for versions j602
Run calc'' in an interactive J session after loading the file. The function calc2 calculates the roots of the equation using J’s built in root function(p.).
print=: 1!:2&2
read=: 3 : '1!:1[1'
a=: 0&{ [ b=: 1&{ [ c=: 2&{
d=: *:@b - [:*/4,a,c
roots=: ([:-b%2*a)`(+:@a %~ (,-)@%:@d + -@b)@.([:*/*)
input=: 3 : 0
A=: ".1!:1[1 [ print 'A = '
B=: ".1!:1[1 [ print 'B = '
C=: ".1!:1[1 [ print 'C = '
)
calc=: 3 : 0
input''
if. A=0 do. print 'Not a quadratic equation' throw. end.
rt=: roots A,B,C
disp rt
)
disp=: 3 : 0
form=: ((('('&,)@":@{.,',',(,&')')@":@}.)@+.)`":@.(=+)
if. 1<# ~.y do.
print 'x1 = ', form 0{y
print 'x2 = ', form 1{y
else.
print 'x = ', form {.y
end.
)
calc2=: 3 : 0
input''
rt=: ;}.p.|.A,B,C
disp rt
)
Example for versions Simply Scala
This example shows that string processing and Math in Scala are implemented similarly to Java.
def output(real: Double, imag: Double): String =
if (imag == 0) ""+real
else "("+real+","+imag+")"
def solve(A: Int, B: Int, C: Int)
{ if (A == 0) print("Not a quadratic equation.")
else
{ def D = B*B - 4*A*C
if (D == 0) print("x = "+output(-B/2.0/A, 0))
else if (D > 0) print("x1 = "+output((-B+Math.sqrt(D))/2.0/A, 0)+"\nx2 = "+output((-B-Math.sqrt(D))/2.0/A, 0))
else print("x1 = "+output(-B/2/A, Math.sqrt(-D)/2.0/A)+"\nx2 = "+output(-B/2/A, -Math.sqrt(-D)/2.0/A))
}
}
Example for versions gawk 3.1.6, mawk 1.3.3
{ A = $1
B = $2
C = $3
if (A == 0)
print "Not a quadratic equation"
else
{ D = B*B-4*A*C
if (D == 0)
print "x = " (-B/2/A)
else if (D > 0)
{ print "x1 = " ((-B+sqrt(D))/2/A)
print "x2 = " ((-B-sqrt(D))/2/A)
}
else
{ print "x1 = (" (-B/2/A) "," (sqrt(-D)/2/A) ")"
print "x1 = (" (-B/2/A) "," (-sqrt(-D)/2/A) ")"
}
}
}