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?
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
Bin baseN+1and you have the coefficients.Attempted explanation: Algebraically, the polynomial is
If you have a number
band expand it in basen, then you getwhere each
b_iis uniquely determined andb_i < n.