这里有一个总结迪米特里斯·安德烈欧 https://stackoverflow.com/questions/3492302/easy-interview-question-got-harder-given-numbers-1-100-find-the-missing-number/3492664#3492664 .
记住 i 次方的和,其中 i=1,2,..,k。这将问题简化为求解方程组
a1 + a2 + ... + ak = b1
a12 + a22 + ... + ak2 = b2
...
a1k + a2k + ... + akk = bk
Using Newton's identities https://en.wikipedia.org/wiki/Newton_identities#Formulation_in_terms_of_symmetric_polynomials, knowing bi allows to compute
c1 = a1 + a2 + ... ak
c2 = a1a2 + a1a3 + ... + ak-1ak
...
ck = a1a2 ... ak
If you expand the polynomial (x-a1)...(x-ak) the coefficients will be exactly c1, ..., ck - see Viète's formulas https://en.wikipedia.org/wiki/Vi%C3%A8te's_formulas. Since every polynomial factors uniquely (ring of polynomials is an Euclidean domain https://en.wikipedia.org/wiki/Euclidean_domain), this means ai are uniquely determined, up to permutation.
这就证明了记住幂就足以恢复数字。对于常数 k,这是一个很好的方法。
However, when k is varying, the direct approach of computing c1,...,ck is prohibitely expensive, since e.g. ck is the product of all missing numbers, magnitude n!/(n-k)!. To overcome this, perform computations in Zq field https://en.wikipedia.org/wiki/Finite_field_arithmetic, where q is a prime such that n <= q < 2n - it exists by Bertrand's postulate https://en.wikipedia.org/wiki/Bertrand's_postulate. The proof doesn't need to be changed, since the formulas still hold, and factorization of polynomials is still unique. You also need an algorithm for factorization over finite fields, for example the one by Berlekamp https://en.wikipedia.org/wiki/Berlekamp's_algorithm or Cantor-Zassenhaus https://en.wikipedia.org/wiki/Cantor%E2%80%93Zassenhaus_algorithm.
常数 k 的高级伪代码:
- 计算给定数字的 i 次方
- Subtract to get sums of i-th powers of unknown numbers. Call the sums bi.
- Use Newton's identities to compute coefficients from bi; call them ci. Basically, c1 = b1; c2 = (c1b1 - b2)/2; see Wikipedia for exact formulas
- Factor the polynomial xk-c1xk-1 + ... + ck.
- The roots of the polynomial are the needed numbers a1, ..., ak.
对于变化的 k,使用例如找到素数 n
EDIT: The previous version of this answer stated that instead of Zq, where q is prime, it is possible to use a finite field of characteristic 2 (q=2^(log n)). This is not the case, since Newton's formulas require division by numbers up to k.