Dados tres enteros a , b y c tales que a + b + c = 0 . La tarea es encontrar las raíces de una ecuación cuadrática ax 2 + bx + c = 0 .
Ejemplos:
Entrada: a = 1, b = 2, c = -3
Salida: 1, -3
Entrada: a = -5, b = 3, c = 2
Salida: 1, -2,5
Planteamiento: Cuando a + b + c = 0 entonces las raíces de la ecuación ax 2 + bx + c = 0 son siempre 1 y c/a .
Por ejemplo,
Toma a = 3, b = 2 y c = -5 tal que a + b + c = 0
Ahora, la ecuación será 3x 2 + 2x – 5 = 0
Resolviendo para x,
3x 2 + 5x – 3x – 5 = 0
x * (3x + 5) -1 * (3x + 5) = 0
(x – 1) * (3x + 5) = 0
x = 1, x = (-5/3) = (c/a)
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to print the roots of the // quadratic equation when a + b + c = 0 void printRoots(long a, long b, long c) { cout << 1 << ", " << c / (a * 1.0); } // Driver code int main() { long a = 2; long b = 3; long c = -5; printRoots(a, b, c); return 0; }
Java
// Java implementation of the approach class GFG { // Function to print the roots of the // quadratic equation when a + b + c = 0 static void printRoots(long a, long b, long c) { System.out.println(1 + ", " + c / (a * 1.0)); } // Driver Code public static void main (String[] args) { long a = 2; long b = 3; long c = -5; printRoots(a, b, c); } } // This code is contributed by // sanjeev2552
Python3
# Python3 implementation of the approach # Function to print the roots of the # quadratic equation when a + b + c = 0 def printRoots(a, b, c): print(1, ",", c / (a * 1.0)) # Driver code a = 2 b = 3 c = -5 printRoots(a, b, c) # This code is contributed by Mohit Kumar
C#
// C# implementation of the approach using System; class GFG { // Function to print the roots of the // quadratic equation when a + b + c = 0 static void printRoots(long a, long b, long c) { Console.WriteLine("1, " + c / (a * 1.0)); } // Driver code public static void Main() { long a = 2; long b = 3; long c = -5; printRoots(a, b, c); } } // This code is contributed by Nidhi
PHP
<?php // PHP implementation of the approach // Function to print the roots of the // quadratic equation when a + b + c = 0 function printRoots($a, $b, $c) { echo "1"; echo ", "; echo $c / ($a * 1.0); } // Driver code $a = 2; $b = 3; $c = -5; printRoots($a, $b, $c); // This code is contributed by Naman_Garg. ?>
Javascript
<script> // Javascript implementation of the approach // Function to print the roots of the // quadratic equation when a + b + c = 0 function printRoots(a, b, c) { document.write(1 + ", " + c / (a * 1.0)); } // Driver code var a = 2; var b = 3; var c = -5; printRoots(a, b, c); // This code is contributed by noob2000. </script>
1, -2.5
Complejidad de tiempo: O(1), solo hay aritmética básica que ocurre en tiempo constante.
Espacio Auxiliar: O(1), no se toma espacio extra.