Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Triangular Matchstick Number
In this article, we will learn how to calculate the total number of matchsticks required to build a triangular pyramid. Given the number of floors X, we need to find the total matchsticks needed to construct the entire pyramid structure.
Problem statement − We are given a number X which represents the floor of a matchstick pyramid, we need to display the total number of matchsticks required to form a pyramid of matchsticks with X floors.
Understanding the Pattern
In a triangular matchstick pyramid:
- Floor 1 requires 3 matchsticks (forming 1 triangle)
- Floor 2 requires 9 matchsticks (forming 3 triangles)
- Floor 3 requires 18 matchsticks (forming 6 triangles)
- Floor n requires 3n(n+1)/2 matchsticks total
Mathematical Formula
The formula to calculate triangular matchstick numbers is:
Total matchsticks = 3 × n × (n + 1) / 2
Where n is the number of floors in the pyramid.
Example
Let's implement the solution to calculate matchsticks for a 21-floor pyramid ?
# Function to calculate triangular matchstick number
def numberOfSticks(x):
return (3 * x * (x + 1)) // 2
# Calculate for 21 floors
n = 21
total_sticks = numberOfSticks(n)
print(f"Matchsticks required for {n} floors: {total_sticks}")
Matchsticks required for 21 floors: 693
Step-by-Step Calculation
Let's verify with smaller examples to understand the pattern ?
def numberOfSticks(x):
return (3 * x * (x + 1)) // 2
# Test with different floor numbers
floors = [1, 2, 3, 4, 5]
print("Floor | Matchsticks")
print("------|------------")
for floor in floors:
sticks = numberOfSticks(floor)
print(f"{floor:5} | {sticks:10}")
Floor | Matchsticks
------|------------
1 | 3
2 | 9
3 | 18
4 | 30
5 | 45
Alternative Implementation
We can also implement using a loop to see how the pattern builds ?
def numberOfSticksLoop(x):
total = 0
for i in range(1, x + 1):
triangles_in_floor = (i * (i + 1)) // 2
total += triangles_in_floor * 3
return total
# Compare both methods
n = 10
method1 = numberOfSticks(n)
method2 = numberOfSticksLoop(n)
print(f"Formula method: {method1}")
print(f"Loop method: {method2}")
print(f"Results match: {method1 == method2}")
Formula method: 165 Loop method: 165 Results match: True
Conclusion
The triangular matchstick number follows the formula 3 × n × (n + 1) / 2. This mathematical approach provides an efficient solution compared to iterative counting, making it ideal for calculating large pyramid structures.
