Problem Description:
28 soldiers went to buy water, 3 empty bottles can be replaced by a bottle of water, ask the most to buy a few bottles of water can make all the soldiers drink water, and do not waste.
Problem Analysis:
The key to this problem is that 3 empty bottles of water will also produce empty bottles, and the first time to buy water bottles is not necessarily a 3 multiples. To understand this, the problem is solved.
If you purchase n bottles of water, then set F (n) as the number of bottles that can be given water, then:
F (n) = (N/3) + ((N/3) + (n%3)/3 + (((N/3) + (n%3)/3 + ((N/3) + (n%3)%3)/3 + ...
So the water we've actually obtained recently has n + f (n) bottles.
The code is as follows (Python implementation):
# Calculate How many extral bottles is free if you buy "num" bottles
def extrabottle (num):
n = int (num)
r = 0 While N/3! =
0:
# Calc Free bottle
r = r + N/3
# Calc Empty bottle number
# (empty ones of free bottle + empty ones of remainder)
n = n/3 + n%3
return r
def bottletobuy (num):
i = Int (1) while
TRUE:
if (i + extrabottle (i) >= num):
break
i + = 1
return i
print bottletobuy (28)
Last Answer: 19