Skip to content

Commit 43daf7e

Browse files
Optimize pyramid height calculation function
Refactor pyramid height calculation to use a mathematical formula instead of iteration.
1 parent 8f523fc commit 43daf7e

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

Week03/pyramid_aysegul_yildiz.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
1-
def calculate_pyramid_height(number_of_blocks):
2-
height = 0
3-
used_blocks = 0
1+
import math
42

5-
for level in range(1, number_of_blocks + 1):
6-
# Taş ihtiyacı: level*(level+1)/2
7-
blocks_needed = level * (level + 1) // 2
3+
def calculate_pyramid_height(n: int) -> int:
4+
if n <= 0:
5+
return 0
86

9-
if used_blocks + blocks_needed > number_of_blocks:
10-
break
7+
# h(h+1)/2 <= n → h ≤ (sqrt(1 + 8*n) - 1) / 2
8+
9+
h = (math.isqrt(1 + 8*n) - 1) // 2
10+
return int(h)
1111

12-
used_blocks += blocks_needed
13-
height = level
14-
15-
return height

0 commit comments

Comments
 (0)