Quadratic equation#911

Quadratic equation (Editorial)

The task is to solve the quadratic equation using the formula

x = \frac{-b \pm \sqrt{d}}{2a},

where is the discriminant of the quadratic equation, equal to b^2 - 4ac.

Depending on the sign of the discriminant, there are three possible cases:

Algorithm implementation

Since the coefficients of the equation and its roots (if they exist) are integers, all computations will be performed using integers. Read the input data.

scanf("%d %d %d", &a, &b, &c);

Compute the discriminant of the quadratic equation.

d = b * b - 4 * a * c;

Depending on the sign of the discriminant, print the answer.

if (d < 0) 
  printf("No roots\n");
else if (d == 0) 
{
  x1 = -b / (2 * a);
  printf("One root: %d\n", x1);
}
else 
{
  x1 = (-b - sqrt(d)) / (2 * a);
  x2 = (-b + sqrt(d)) / (2 * a);
  printf("Two roots: ");
  if (x1 < x2) 
    printf("%d %d\n", x1, x2);
  else 
    printf("%d %d\n", x2, x1);
}

Java implementation

import java.util.*;

public class Main
{
  public static void main(String []args)
  {
    Scanner con = new Scanner(System.in);
    int a = con.nextInt();
    int b = con.nextInt();
    int c = con.nextInt();
  
    int d = b * b - 4 * a * c;
    double x1 = (-b - Math.sqrt(d)) / (2 * a);
    double x2 = (-b + Math.sqrt(d)) / (2 * a);

    if (d == 0) 
      System.out.printf("One root: %.0f\n", x1);
    else if (d < 0) 
      System.out.printf("No roots\n");
    else if (x1 < x2) 
      System.out.printf("Two roots: %.0f %.0f\n", x1, x2);
    else 
      System.out.printf("Two roots: %.0f %.0f\n ", x2, x1);

    con.close();
  }
} 

Python implementation

import math

Since the coefficients of the equation and its roots (if they exist) are integers, all computations will be performed using integers. Read the input data.

a, b, c = map(int, input().split())

Compute the discriminant of the quadratic equation.

d = b * b - 4 * a * c

Depending on the sign of the discriminant, print the answer.

if d < 0:
  print("No roots")
elif d == 0:
  x1 = -b // (2 * a)
  print("One root:", x1)
else:
  x1 = int((-b - math.sqrt(d)) // (2 * a))
  x2 = int((-b + math.sqrt(d)) // (2 * a))
  print("Two roots:", min(x1, x2), max(x1, x2))