• + 4 comments

    Well, not sure about this formula but if you wanted to use one yourself, think about the steps you would take if you were doing the exchange of wrappers by hand; by the way, not the best code to write as it's confusing and you are writing over the money variable instead of creating a new one. First you buy as many chocolates as you want, chocolates = money/cost . Now you eat those chocolates and exchange all the wrappers possible for extra ones, let's call it extras = chocolates / extra .

    BUT you could have leftover chocolates so let's see how many, remainders = chocolates % extra . Since we got extras , we can add it to the remainders and see if it is enough for more chocolates, super_extras = (extras + remainders) / extra . Remember that all of this is integer division so it'll round down.

    Finish by adding to the total chocolates += extras + super_extras and you're done! You have to tweak it a bit to get edge cases but that part should be trivial. Use the same logic to see where those terms you wrote came from. I think if you rearrange what I showed you'll get the same thing.