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
andx2
).
Equation will be the form ofax^2 + bx + c = 0
Return typeis 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 fixa = 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 becomesx^2 - 3x + 2 = 0
Example 2
quadratic(0,1) = (1, -1, 0)
This means(x-0) * (x-1) = 0
x^2 - x + 0 = 0
Notes
- Inputs will be integers.
- When
x1 == x2
, this means the root has the multiplicity of two