Roots of the quadratic equation when a + b + c = 0 without using Shridharacharya formula
Last Updated :
28 May, 2022
Given three integers a, b and c such that a + b + c = 0. The task is to find the roots of a quadratic equation ax2 + bx + c = 0.
Examples:
Input: a = 1, b = 2, c = -3
Output: 1, -3
Input: a = -5, b = 3, c = 2
Output: 1, -2.5
Approach: When a + b + c = 0 then the roots of the equation ax2 + bx + c = 0 are always 1 and c / a.
For example,
Take a = 3, b = 2 and c = -5 such that a + b + c = 0
Now, the equation will be 3x2 + 2x – 5 = 0
Solving for x,
3x2 + 5x – 3x – 5 = 0
x * (3x + 5) -1 * (3x + 5) = 0
(x – 1) * (3x + 5) = 0
x = 1, x = (-5 / 3) = (c / a)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printRoots( long a, long b, long c)
{
cout << 1 << ", " << c / (a * 1.0);
}
int main()
{
long a = 2;
long b = 3;
long c = -5;
printRoots(a, b, c);
return 0;
}
|
Java
class GFG
{
static void printRoots( long a, long b, long c)
{
System.out.println( 1 + ", " + c / (a * 1.0 ));
}
public static void main (String[] args)
{
long a = 2 ;
long b = 3 ;
long c = - 5 ;
printRoots(a, b, c);
}
}
|
Python3
def printRoots(a, b, c):
print ( 1 , "," , c / (a * 1.0 ))
a = 2
b = 3
c = - 5
printRoots(a, b, c)
|
C#
using System;
class GFG
{
static void printRoots( long a, long b, long c)
{
Console.WriteLine( "1, " + c / (a * 1.0));
}
public static void Main()
{
long a = 2;
long b = 3;
long c = -5;
printRoots(a, b, c);
}
}
|
PHP
<?php
function printRoots( $a , $b , $c )
{
echo "1" ;
echo ", " ;
echo $c / ( $a * 1.0);
}
$a = 2;
$b = 3;
$c = -5;
printRoots( $a , $b , $c );
?>
|
Javascript
<script>
function printRoots(a, b, c)
{
document.write(1 + ", " + c / (a * 1.0));
}
var a = 2;
var b = 3;
var c = -5;
printRoots(a, b, c);
</script>
|
Time Complexity: O(1), there is only basic arithmetic that happens in constant time.
Auxiliary Space: O(1), no extra space is taken.
Share your thoughts in the comments
Please Login to comment...