给定两个整数S和M ,任务是找到二次方程的系数,使得根的总和和乘积分别为S和M。
例子:
Input: S = 5, M = 6
Output: 1 -5 6
Explanation:
For the quadratic equation x2 – 5x + 6 = 0. The root of the equation are 2 and 3. Therefore, the sum of roots is 2 + 3 = 5, and the product of roots is 2*3 = 6.
Input: S = -2, M = 1
Output: 1 2 1
方法:可以通过使用二次方程的属性来解决给定的问题,如下所示:
For the above quadratic equation the roots are given by:
and
The sum of roots is given by:
=>
=>
=>
The product of roots is given by:
=>
=>
根据以上两个方程,如果a的值为1,则b的值为(-1)* S , c为P。因此,该等式由下式给出:
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the quadratic
// equation from the given sum and
// products of roots
void findEquation(int S, int M)
{
// Print the coefficients
cout << "1 " << (-1) * S << " "
<< M << endl;
}
// Driver Code
int main()
{
int S = 5, M = 6;
findEquation(S, M);
return 0;
}
输出:
1 -5 6
时间复杂度: O(1)
辅助空间: O(1)