Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too.
A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25...
Complete the beeramid function to return the number of complete levels of a beer can pyramid you can make, given the parameters of:
1) your referral bonus, and
2) the price of a beer can
For example:
beeramid(1500, 2); // should === 12
beeramid(5000, 3); // should === 16
Tests:
beeramid(9, 2)
beeramid(21, 1.5)
beeramid(-1, 4)
This challenge comes from kylehill on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (5)
Clojure. Not very terse, but it gets a solution in constant time
Testing:
To follow up on my solution, I borrowed from the Wikipedia article on Square Pyramidal Numbers. This provides a formula for the sum of squares as a special case of Faulhaber's formula:
As n becomes large then: 2n3 ≫ 3n2 + n
Using this method, a small numbers of cups will require 2 guesses, but as the number of cups gets higher (and n3 ≫ n2) then it is more likely to get it on the first guess. I told it to keep testing while the number of layers until 1, but it never actually gets beyond 2 attempts.
Here's my C solution,
Notice that there is no need for any iteration because (taking number of cans = N and number of levels = L)
Here is a Python Solution,
Test Cases,
Haskell solution using lazy, infinite list of cans: