# How to solve triangular matchstick number in Python

In this tutorial, let’s see how to solve the triangular matchstick number in Python. It is a well-known problem and is as follows:

Given the number of sub-triangles in the base layer of the bigger triangle, find the total number of matchsticks required to build the overall triangle until there is a single triangle at the top. You can refer to the below picture for more clarification.

In the above picture, consider each triangle to be made of 3 matchsticks. So the objective of the problem is to find the total number of matchsticks required to build the whole triangle. Before we look at the solution, take a few moments to think of a possible solution.

**The idea behind the solution:**

It is quite clear from the picture that the numbers of triangles at each level decreases by 1 starting at the bottom. If the bottom layer has T sub triangles, the layer above it will have T – 1 sub triangles and so on until the topmost layer has 1 triangle. So it is clear that the final triangle will have T + (T – 1) + (T – 2) + … + 1 sub triangles which is also equal to (T * (T + 1)) / 2. Multiply it with the number of sticks required for each sub triangle and you will have the final answer. So the final solution comes down to one simple formula: 3 * (T * (T + 1)) / 2.

## How to solve triangular matchstick number in Python:

# Number of sub triangles in the base layer T = int(input()) # Total number of sub triangles subtriangles = (T * (T + 1)) // 2 # Total number of sticks required stick_count = subtriangles * 3 print("The number of matchsticks required is", stick_count)

As you can see, we have solved the problem quite easily. I hope you found this article helpful in solving the problem.

See also:

## Leave a Reply

You must be logged in to post a comment.