Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Number of triangles after N moves
Next article icon

Number of triangles after N moves

Last Updated : 17 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Find the number of triangles in Nth step, 
Rules: Draw an equilateral triangle at the start. In the i-th move, take the uncolored triangles, divides each of them in 4 parts of equal areas and color the central part. Keep a count of triangles till the Nth step.

Examples:  

Input : 1  Output : 5   Explanation: In 1st move we get

Number of triangles after N moves example 1

Input : 2  Output : 17   Explanation: In 2nd move we get

Number of triangles after N moves example 2

Naive approach: 
The number of triangles in the nth figure are 3 times the number of triangles in the (n-1)th figure+2. We can see by observation the nth figure is made by placing 3 triangles similar to that in (n-1) figure and an inverted triangle. We also take into account the bigger triangle that has been formed. Hence the number of triangles in the nth figure becomes (number of triangles in the (n-1)th figure)*3 + 2. 

C++
// C++ program to calculate the number of equilateral // triangles #include <bits/stdc++.h> using namespace std; // function to calculate number of triangles in Nth step int numberOfTriangles(int n) {     int answer[n + 1] = { 0 };     answer[0] = 1;     for (int i = 1; i <= n; i++)          answer[i] = answer[i - 1] * 3 + 2;          return answer[n]; }  // driver program  int main() {     int n = 2;     cout << numberOfTriangles(n);     return 0; } 
Java
// Java program to find middle of three  // distinct numbers to calculate the  // number of equilateral triangles import java.util.*;  class Triangle {        // function to calculate number of      // triangles in Nth step     public static int numberOfTriangles(int n)     {         int[] answer = new int[n+1];         answer[0] = 1;                  for (int i = 1; i <= n; i++)              answer[i] = answer[i - 1] * 3 + 2;              return answer[n];     }          // driver code     public static void main(String[] args)     {         int n = 2;         System.out.println(numberOfTriangles(n));     } }  // This code is contributed by rishabh_jain 
Python3
# Python3 code to calculate the  # number of equilateral triangles  # function to calculate number  # of triangles in Nth step def numberOfTriangles (n) :     answer = [None] * (n + 1);     answer[0] = 1;     i = 1     while i <= n:          answer[i] = answer[i - 1] * 3 + 2;         i = i + 1          return answer[n];  # Driver code n = 2 print(numberOfTriangles(n))  # This code is contributed by "rishabh_jain". 
C#
// C# program to find middle of three  // distinct numbers to calculate the  // number of equilateral triangles using System;  class Triangle {      // function to calculate number of      // triangles in Nth step     public static int numberOfTriangles(int n)     {         int[] answer = new int[n+1];         answer[0] = 1;                  for (int i = 1; i <= n; i++)              answer[i] = answer[i - 1] * 3 + 2;              return answer[n];     }          // Driver code     public static void Main()     {         int n = 2;         Console.WriteLine(numberOfTriangles(n));     } }  // This code is contributed by vt_m 
PHP
<?php // PHP program to calculate // the number of equilateral // triangles  // function to calculate number // of triangles in Nth step function numberOfTriangles($n) {     $answer = array();     $answer[0] = 1;     for ($i = 1; $i <= $n; $i++)          $answer[$i] = $answer[$i - 1] *                                 3 + 2;          return $answer[$n]; }      // Driver Code     $n = 2;     echo numberOfTriangles($n);  // This code is contributed by anuj_67. ?> 
JavaScript
<script>  // Javascript program to calculate  // the number of equilateral // triangles  // Function to calculate number // of triangles in Nth step function numberOfTriangles(n) {     let answer = new Uint8Array(n + 1);     answer[0] = 1;          for(let i = 1; i <= n; i++)         answer[i] = answer[i - 1] * 3 + 2;          return answer[n]; }  // Driver code let n = 2;  document.write(numberOfTriangles(n));      // This code is contributed by Mayank Tyagi      </script> 

Output
17

Time Complexity: O(n)
Auxiliary Space: O(n)

An efficient solution will be to derive a formula for Nth step: 
If we follow the naive approach for every step, then we get for Nth step the number of triangles to be  

(2*(3^n))-1. 

C++
// C++ program to calculate the number of  // equilateral triangles #include <bits/stdc++.h> using namespace std;  // function to calculate number of triangles  // in Nth step int numberOfTriangles(int n) {     int ans = 2 * (pow(3, n)) - 1;     return ans; }  // driver program  int main() {     int n = 2;     cout << numberOfTriangles(n);     return 0; } 
Java
// Java program to find middle of three  // distinct numbers to calculate the // number of equilateral triangles import java.util.*; import static java.lang.Math.pow;  class Triangle {        // function to calculate number      // of triangles in Nth step     public static double numberOfTriangles(int n)     {         double ans = 2 * (pow(3, n)) - 1;         return ans;     }          // driver code     public static void main(String[] args)     {         int n = 2;         System.out.println(numberOfTriangles(n));     } }  // This code is contributed by rishabh_jain 
Python3
# Python3 code to calculate the  # number of equilateral triangles  # function to calculate number # of triangles in Nth step def numberOfTriangles (n) :     ans = 2 * (pow(3, n)) - 1;     return ans;  # Driver code n = 2 print (numberOfTriangles(n))  # This code is contributed by "rishabh_jain". 
C#
//C# program to find middle of three  // distinct numbers to calculate the // number of equilateral triangles using System;  class Triangle {      // function to calculate number      // of triangles in Nth step     public static double numberOfTriangles(int n)     {         double ans = 2 * (Math.Pow(3, n)) - 1;         return ans;     }          // Driver code     public static void Main()     {         int n = 2;         Console.WriteLine(numberOfTriangles(n));     } }  // This code is contributed by vt_m 
PHP
<?php // PHP program to calculate the  // number of equilateral triangles  // function to calculate  // number of triangles  // in Nth step function numberOfTriangles($n) {     $ans = 2 * (pow(3, $n)) - 1;     return $ans; }      // Driver Code     $n = 2;     echo numberOfTriangles($n);  // This code is contributed by anuj_67. ?> 
JavaScript
<script> // javascript program to find middle of three  // distinct numbers to calculate the // number of equilateral triangles      // function to calculate number     // of triangles in Nth step     function numberOfTriangles(n)      {         var ans = 2 * (Math.pow(3, n)) - 1;         return ans;     }      // Driver code         var n = 2;         document.write(numberOfTriangles(n));  // This code is contributed by aashish1995 </script> 

Output
17

Time Complexity: O(log n), due to the inbuilt pow() function.
Auxiliary Space: O(1)


Next Article
Number of triangles after N moves

S

Striver
Improve
Article Tags :
  • Misc
  • Mathematical
  • DSA
  • Basic Coding Problems
  • triangle
Practice Tags :
  • Mathematical
  • Misc

Similar Reads

    Count number of 1s in the array after N moves
    Given an array of size N in which initially all the elements are 0(zero). The task is to count the number of 1's in the array after performing N moves on the array as explained:In each move (starting from 1 to N) the element at the position of the multiple of the move number is changed from 0 to 1 o
    9 min read
    Count the total number of triangles after Nth operation
    Given an equilateral triangle, the task is to compute the total number of triangles after performing the following operation N times. For every operation, the uncolored triangles are taken and divided into 4 equal equilateral triangles. Every inverted triangle formed is colored. Refer to the below f
    3 min read
    Number of Isosceles triangles in a binary tree
    Pre-Requisites: Depth First Search | Parent Array RepresentationGiven a parent array representation of a binary tree, we need to find the number of Isosceles triangles in the binary tree. Consider a parent array representing a binary tree: Parent Array: Given below is the tree representation of the
    13 min read
    Number of Triangles in an Undirected Graph
    Given an Undirected simple graph, We need to find how many triangles it can have. For example below graph have 2 triangles in it. Let A[][] be the adjacency matrix representation of the graph. If we calculate A3, then the number of triangles in Undirected Graph is equal to trace(A3) / 6. Where trace
    14 min read
    Centered triangular number
    Given an integer n, find the nth Centered triangular number. Centered Triangular Number is a centered polygonal number that represents a triangle with a dot in the center and all other dots surrounding the center in successive triangular layers [Source : Wiki ] Pictorial Representation : The first f
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences