You all know the lyrics to the song "99 Bottles of Beer on the Wall", right? If not check out this link.
Instead of removing just one bottle in each iteration, we want to remove one more bottle than in the previous iteration (i.e. start with 99, then 98, then 96, 93, 89, etc.)
The Challenge: Write a method that takes the initial number of beers on the wall and returns the number of iterations needed to remove all the bottles, in addition to providing the number of bottles removed in the last iteration. (as a tuple or as a string).
Bonus — do the math, not just a simple loop (because that wouldn't be much of a challenge, would it?)
Good luck!
This challenge comes from @peledzohar here on DEV. Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (5)
My solution in Swift (without Bonus it's saturday 😛) :
Edit: Thank you to @vo_kononenko for to find my mistake
It looks like
number *= 2
at the end of the loop should be replaced withnumber += 1
, because the number of removed bottles on each iteration increases by 1, not doubles.It's right ! I do that too fastly. Thank you for your attention.
Here is O(log(n)) solution using Kotlin. We use the arithmetic progression formula to calculate the sum from 1 to n without a loop with O(1) complexity. And after we use the binary search to find the number of iterations needed with O(log(n)) complexity. This will work for very large values of n, although I do not think anybody will have such a big number of beers on the wall:)
Result for n=Long.MAX_VALUE=9223372036854775807 is (4294967296, 2147483647).
This is as close as I can get to “no string declared more than once”