问题
I keep getting these hard interview questions. This one really baffles me.
You're given a function poly
that takes and returns an int
. It's actually a polynomial with nonnegative integer coefficients, but you don't know what the coefficients are.
You have to write a function that determines the coefficients using as few calls to poly
as possible.
My idea is to use recursion knowing that I can get the last coefficient by poly(0)
. So I want to replace poly
with (poly - poly(0))/x
, but I don't know how to do this in code, since I can only call poly
. ANyone have an idea how to do this?
回答1:
Here's a neat trick.
int N = poly(1)
Now we know that every coefficient in the polynomial is at most N
.
int B = poly(N+1)
Now expand B
in base N+1
and you have the coefficients.
Attempted explanation: Algebraically, the polynomial is
poly = p_0 + p_1 * x + p_2 * x^2 + ... + p_k * x^k
If you have a number b
and expand it in base n
, then you get
b = b_0 + b_1 * n + b_2 * n^2 + ...
where each b_i
is uniquely determined and b_i < n
.
来源:https://stackoverflow.com/questions/6636878/print-a-polynomial-using-minimum-number-of-calls