codewar刷题--8kyu--Coefficients of the Quadratic Equation

这个题目是说,给出了一个一元二次方程的两个整数根,根据根去算每个根前面的系数,等等一个整数的系数信息,让方程式成立。

在考初中知识,老大叔已经忘了一元二次方程式的解公式,表示很无奈的只能去问度娘。

找到的是韦氏公式,信息如下:

根与系数之间的关系又称韦达定理,指的是如果方程ax平方+bx+c=0(a不等于0)的两根为x1、x2,那么x1+x2=-b/a,x1x2=c/a

因为已经设定了根是整数,所以a 直接设置为1就好了。因为x1+x2=-b/a 是整数,-b/a 就一定是整数。

根据韦氏公式计算出来b 和c的值就可以了。

def quadratic(x1, x2):
    a=1
    b=0-(x1+x2)
    c=x1*x2
    return(a,b,c)

原题目:

In this Kata you are expected to find the coefficients of quadratic equation of the given two roots (x1 and x2).

Equation will be the form of ax^2 + bx + c = 0

Return type is a Vector (tuple in Rust, Array in Ruby) containing coefficients of the equations in the order (a, b, c).

Since there are infinitely many solutions to this problem, we fix a = 1.

Remember, the roots can be written like (x-x1) * (x-x2) = 0

Example

quadratic(1,2) = (1, -3, 2)

This means (x-1) * (x-2) = 0; when we do the multiplication this becomes x^2 - 3x + 2 = 0

Example 2

quadratic(0,1) = (1, -1, 0)

This means (x-0) * (x-1) = 0; when we do the multiplication this becomes x^2 - x + 0 = 0

Notes

  • Inputs will be integers.
  • When x1 == x2, this means the root has the multiplicity of two

 

posted @ 2020-07-18 10:59  senjy  Views(265)  Comments(0)    收藏  举报