I tried doing it reverse order, and came at a guess of 524288 or 38, don't suppose you have the answer do you? =)
I've been playing with this for a bit and found out the following.
We may derive an expression for g(x) by considering the decomposition of x into . In this way we may derive a recursively defined series that generates a value for any g(x) in terms of n and r. I have not carried out the full treatment, but have derived the following table:
I think you can guess how the pattern goes from this.
So to find g(5), for example, we do the following: . This is of the form where n = 2. So . Thus g(5) = 5 as expected.
We wish to find x such that g(x) = 20. We have several possibilities just in the small table I derived above:
etc.
So I've got g(1048576) = g(2056) = g(1027) = g(1026) as just some possibilities.
Once you derive the general relationship you should be able to just write x in terms of n and r.
(By the way, double check 4181; I'm getting g(4181) = 18.)
-Dan