Issue
So for this coding exercise I have to input a number of imaginary blocks and it will tell me how many complete rows high the pyramid is.
So for example if I input 6 blocks...I want it to tell me that the height of the pyramid is 3. (3 blocks on the bottom, 2 above that, and 1 above that).
In my head I feel this would work similar to a Fibonacci pyramid so I based my code off of that.
blocks = int(input("Enter number of blocks: "))
for i in range(blocks + 1):
for j in range(blocks + 1):
height = j / 2
if height % 2 == 0:
height = height / 2
print(f"The height of the pyramid: {height}")
This is what I have so far... If I do the number 6 or like 20 it works, but obviously if I do something like 1000 it isn't going to give me the result I want. I feel I'm pretty far off with my code.
Solution
A pyramid of height N
has 1 + 2 + ... + N
blocks in it. This reduces toN * (N + 1) / 2
. So you need to find the largest integer of the form (N^2 + N) / 2
that is less than or equal to your chosen number blocks
. The quadratic is fairly simple: N^2 + N - 2 * blocks = 0
, with roots at N = floor((-1 +/- sqrt(1 + 8 * blocks)) / 2)
. Since blocks
is a positive integer, the negative root will never apply in your case. You can use int
for floor
and **0.5
for sqrt
to get:
blocks = int(input("Enter number of blocks: "))
print(f'You can build a pyramid {int(0.5 * ((8 * blocks + 1)**0.5 - 1))} blocks high')
Answered By - Mad Physicist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.