In the game Pokémon Go, you need a fixed number of candies to evolve one Pokémon belonging to a given species. However, when you transfer the evolved Pokémon, it gives you one candy back. For instance, a pidgey costs 12 candies to evolve. If you start with 498 such candies, you can evolve 41 pidgeys on the first round, 3 on the second round, and 1 on the last round, resulting in 45 evolutions.
I can easily write an iterative algorithm to calculate that:
def evolve_and_transfer(candies, evolution_cost):
result = 0
i = 1
while candies >= evolution_cost:
(evolutions, candies) = divmod(candies, evolution_cost)
print("Round %s: %s evolutions, %s candies remain." % (i, evolutions, candies))
candies += evolutions
result += evolutions
i += 1
return result
assert evolve_and_transfer(498, 12) == 45
But I wonder whether there exists a closed formula which calculates the same function, and could be implemented without loops.
With:
Then:
$$ E = \begin{cases} 0 & \text{if $A=0$}\\ \lfloor\frac{A-1}{N-1}\rfloor & \text{otherwise} \end{cases} $$