DEV Community

Discussion on: Daily Challenge #230 - Beeramid

Collapse
 
quoll profile image
Paula Gearon

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:

Pn=k=1nk2=2n3+3n2+n6 P_n = \sum_{k=1}^n k^2 = \frac {2n^3 + 3n^2 + n} 6
So if we have n layers, then that will have a total of Pn cups.
As n becomes large then: 2n3 ≫ 3n2 + n
Pn=2n36+(3n2+n6)Pn>n33P_n = \frac {2n^3} 6 + \Big( \frac {3n^2 + n} 6 \Big) \newline P_n > \frac {n^3} 3 \newline
Since the layers is n and the cups in the pyramid is Pn then this gives a bound of:
layers<3cups3layers < \sqrt[3]{3 \cdot cups}
Consequently, my code creates an estimate of the number of layers using this formula, and counts down from there applying the Faulhaber formula to check if the result is less than or equal to the provided number of cups.

Using this method, a small numbers of cups will require 2 guesses, but as the number of cups gets higher (and n3n2) 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.