# Find the Number of Triangles After N Moves using C++

C++Server Side ProgrammingProgramming

n the article, first, we have to draw a colored triangle. We need to take an uncolored triangle and divide the triangle into four small equilaterals. Triangles with the same area and keep doing it till the nth step and find the number of equilateral triangles present in the figure.

## Approach to find The Solution

There are Two Approaches for this Solution and they are −

## Brute Force Approach

We can observe that the number of triangles keeps increasing by some number (increasing by 3*previous_number + 2) after every step. So we can run a loop till n and calculate the number of triangles.

## Example

#include <iostream>
using namespace std;
int main() {
int n = 2; // number of operations we made
int count = 1; // at first we have only one triangle
for(int i = 0; i < n; i++) { // looping till n
count = 3 * count + 2; // as the triangle count is increasing by 3*prev + 2
}
cout <<count << "\n";
}

## Output

17

The time complexity of the program above is O(N), where N is the number of operations performed. Now we can further improve its time complexity which will be very helpful when we deal with higher constraints.

## Efficient Approach

In this approach, we will make up a formula that will calculate our answer for us.

## Example

#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 2; // number of operations we made
int count;
count = 2 * (pow(3, n)) - 1; // the total number of triangles after nth move
cout << count << "\n";
}

## Output

17

The above code has a time complexity of O(log(N)), where N is the number of moves we performed.

## Explanation of the above code

In the given program, we are simply making up a formula to solve our given procedure and putting the values required in the formula, and printing the result.

## Conclusion

This article finds the number of triangles after N moves by applying some observations and some maths. We also learned the C++ program for this problem and the complete approach (Normal and efficient ) by which we solved this problem.

We can write the same program in other languages such as C, java, python, and other languages. we hope you find this article helpful.