Interview Question
Country: United States
perfect, thank you. i have updated the question little bit to also generalize.
for generalizations polynomial of degree k can be used however the computational complexity might increase
degree 3: cubic: ax^3+bx^2+cx+d
and so on
codified - the case for power 2
/**
* solveQuadraticEquation
*
* @param a
* @param b
* @param c
*/
private void solveQuadraticEquation(int a, int b, int c){
double root1 = 0;
double root2 = 0;
double discrimnant = b * b - 4 * a * c;
if( discrimnant == 0 ){ //roots are equal
root1 = root2 = (-b / (2 * a));
}
else if( discrimnant < 0 ){ //imaginary roots
}
else{
root1 = (-b + Math.sqrt(discrimnant)) / (2 * a);
root2 = (-b - Math.sqrt(discrimnant)) / (2 * a);
}
if( root1 < 0 ) root1 = -1 * root1;
if( root2 < 0 ) root2 = -1 * root2;
System.out.println((int) root1 + "," + (int) root2);
}
vector<double> solveQuadraticEquation(int a, int b, int c){
const double epsilon = 0.0000001;
double discrimnant = b*b - 4.0*a*c;
vector<double> res;
if(abs(discrimnant) <= epsilon){
res.push_back(-b/2.0/a);
}
if(discrimnant>epsilon){
discrimnant = sqrt(discrimnant);
res.push_back((-b + discrimnant)/2.0/a);
res.push_back((-b - discrimnant)/2.0/a);
}
return res;
}
x + y = 7 => y = 7-x
- cereskara December 10, 2014Plug into second equation
x^2 + (7-x)^2 = 29
=> x^2 + 49 -14x +x^2 = 29
=> 2x^2 -14x + 20 = 0
Use quadratic equation/ complete the square or whatever you want. I'll do quadratic.
(14 +- sqrt(14^2 - 4(2)(20))) / 2(2)
=> x = 2, 5
Plug it back into one of the equations of your choice, I'll use the first
x = 2
2 + y = 7
y = 5
x = 5
5 + y = 7
y = 2
Our two pair of solutions are (x=2, y=5) and (x=5, y=2)
Edit: On the generalizing part, what you're talking about are systems of equations. What the solutions mean are basically what pairs points of x and y satisfy all of the equations.
Visually, what this means is if you graph them, at what points do they all intersect?
The set of solutions can be finite - they intersect at some points, infinite - they overlap each other so intersect at all their points, empty - they do not intersect.
What you're also asking about for cubic, quartic, . . . this touches on the Abel-Ruffini Theorem. Some brilliant and peculiar mathematicians about 200 years ago proved that there are no general solutions/equations for polynomial degree 5 or higher. The degree being the highest integer power of x.
Finding solutions for these polynomials are done algorithmically. Newton's method, which you may have learned about, is one of them.