Repository navigation
Expand file tree
/
Copy pathcandles.js
More file actions
44 lines (36 loc) · 1.43 KB
/
Copy pathcandles.js
File metadata and controls
44 lines (36 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
When a candle finishes burning it leaves a leftover. makeNew leftovers
can be combined to make a new candle, which, when burning down, will
in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total
number of candles you can burn, assuming that you create new candles
as soon as you have enough leftovers?
Example
For candlesNumber = 5 and makeNew = 2, the output should be
candles(candlesNumber, makeNew) = 9.
Here is what you can do to burn 9 candles:
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
*/
function candles(candlesNumber, makeNew) {
let leftovers = candlesNumber;
let currentCandles = candlesNumber;
let result = 0;
while (currentCandles !== 0) {
result+= currentCandles;
currentCandles = Math.floor(leftovers/makeNew); //2 //1 //1
let rest = leftovers%makeNew; //1 //1 //0
leftovers = rest+currentCandles // 1+2 = 3// 2 0+1//1
}
return result;
}
console.log(candles(5, 2)) //9
console.log(candles(1, 2)) //1
console.log(candles(3, 3)) //4
console.log(candles(11, 3)) //16