Water Bottles

easy math simulation

Problem

You buy numBottles full water bottles. Every bottle you drink becomes an empty bottle, and the shop lets you swap exactly numExchange empties for one new full bottle. Trades can be repeated as long as you can afford them.

Return the maximum total number of bottles you can drink. Constraints: 1 ≤ numBottles ≤ 100 and 2 ≤ numExchange ≤ 100.

InputnumBottles = 9, numExchange = 3
Output13
Drink 9, trade 9 empties for 3 more, drink them, trade those 3 empties for 1 last bottle: 9 + 3 + 1 = 13.

def num_water_bottles(num_bottles, num_exchange):
    total = num_bottles          # drink every bottle we start with
    empty = num_bottles          # they all become empties
    while empty >= num_exchange:
        gained = empty // num_exchange
        total += gained          # drink the freshly traded bottles
        empty = empty % num_exchange + gained
    return total
function numWaterBottles(numBottles, numExchange) {
  let total = numBottles;        // drink every bottle we start with
  let empty = numBottles;        // they all become empties
  while (empty >= numExchange) {
    const gained = Math.floor(empty / numExchange);
    total += gained;             // drink the freshly traded bottles
    empty = empty % numExchange + gained;
  }
  return total;
}
int numWaterBottles(int numBottles, int numExchange) {
    int total = numBottles;      // drink every bottle we start with
    int empty = numBottles;      // they all become empties
    while (empty >= numExchange) {
        int gained = empty / numExchange;
        total += gained;         // drink the freshly traded bottles
        empty = empty % numExchange + gained;
    }
    return total;
}
int numWaterBottles(int numBottles, int numExchange) {
    int total = numBottles;      // drink every bottle we start with
    int empty = numBottles;      // they all become empties
    while (empty >= numExchange) {
        int gained = empty / numExchange;
        total += gained;         // drink the freshly traded bottles
        empty = empty % numExchange + gained;
    }
    return total;
}
Time: O(log numBottles) Space: O(1)