设p(x)是多项式。我们说a是多重k of p(x)的根,如果存在另一个多项式s(x),例如p(x)=s(x)(x-a)^k和s(a)\ne0。
例如,多项式p(x)=x^3+2x^2-7x+4=(x+4)(x-1)^2以1和-4作为根。1是多重性2的根。-4是多重性1的根。
给出一个非零多项式p(x)和它的根a,求出a的多重性。
p(x)的系数都是整数。a也是一个整数。
你可以采取任何合理的形式多项式。例如,多项式x^4-4x^3+5x^2-2x可以表示为:
[1,-4,5,-2,0];[0,-2,5,-4,1];x:"x^4-4*x^3+5*x^2-2*x";x^4-4*x^3+5*x^2-2*x。当你把输入作为一个系数的列表时,你可以假设前导系数(第一个降序)是非零的。
这是密码-高尔夫,所以以字节为单位的最短代码获胜。
在这里,我按降序使用系数列表:
[1,2,-7,4], 1 -> 2
[1,2,-7,4], -4 -> 1
[1,-4,5,-2,0], 0 -> 1
[1,-4,5,-2,0], 1 -> 2
[1,-4,5,-2,0], 2 -> 1
[4,0,-4,4,1,-2,1], -1 -> 2
[1,-12,60,-160,240,-192,64,0], 2 -> 6发布于 2022-10-16 13:47:52
发布于 2022-10-16 13:56:48
期望(root)(polynomial),其中多项式是按升序排列的系数列表。
(r,s=0)=>g=p=>s?-1:1+g(p.map((c,i)=>(s+=c*r**i,c*i)).slice(1))这简单地递归地计算多项式的连续导数:
直到P_k(r)\neq 0并返回迭代次数。
( // outer function taking:
r, // the root r
s = 0 // the sum s of the polynomial evaluation
) => //
g = p => // inner recursive function taking the polynomial p[]
s ? // if s is not equal to 0:
-1 // stop the recursion and decrement the final result
: // else:
1 + // increment the final result
g( // do a recursive call with the derivative of p[]:
p.map((c, i) => // for each coefficient c at position i in p[]:
( //
s += // add to s:
c * // the coefficient multiplied by
r ** i, // the root raised to the power of i
c * i // set the new coefficient to c * i
) //
).slice(1) // end of map(); remove the leading term
) // end of recursive call一个没有slice()的版本,由@tsh建议。
(r,s=k=0)=>g=p=>s?~k:g(p.map(c=>(s+=0|c*r**i,c*i++),i=k--))发布于 2022-10-16 19:16:29
f=lambda p,r,c=0:(q:=[c:=b+c*r for b in p])!=c==0and-~f(q[:-1],r)除以线性因子X-根,如果余数为零,则递归.
https://codegolf.stackexchange.com/questions/253294
复制相似问题