Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a polynomial using minimum number of calls

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?

like image 723
Daniel Avatar asked Jul 09 '11 19:07

Daniel


1 Answers

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.

like image 169
PengOne Avatar answered Oct 21 '22 12:10

PengOne