Problem: given n coconuts, find the maximum number of people p such that perform a process, which give 1 coconut to the monkey and hide exactly 1/p coconuts, repeatedly p times and the remaining coconuts can be divided into p equal shares.
Size: it is believed that input number is less than signed 32-bit integer (2^31), but it is not specified.
Solution: for a given number of people p, the minimun number of coconuts n can be calculated by
1) find x, y such that x * p^(p+1) = y * (p-1)^p - sum{1 <= i <= p}{(p-1)^i * p^(p-i)}, and
2) the minimun n is y mod p^(p+1)
The above equation in step 1 is expaned from the whole sharing process, and the algorithm to finish step 1 is exactly extended euclidean algorithm. In step 2, it is observed that all solutions n are equivalent onder modular operation of given p. Building a table of min n(p) for small p can find the max p for given n effectively.
In this problem with n limited to 2^32 or 2^64, the maximum p is less than 30, and thus simulating the process with all possible p is efficient.
Note: the spec does not limit the last p shares from 0, and then n = 3 has a solution of p = 2.
Speeding up: iterately simulating 2 <= p <= 9 can cover all n n for 2 <= p <= 9 and computing modular is also fast. Efficient I/O operation is required since the computation time is little.