📜  计算第N次运算后的三角形总数

📅  最后修改于: 2021-04-22 08:25:53             🧑  作者: Mango

给定等边三角形,任务是在执行以下N次操作后计算三角形的总数。
对于每次操作,均取无色三角形并将其分成4个相等的等边三角形。形成的每个倒三角形都是彩色的。有关更多详细信息,请参见下图。
对于N = 1 ,形成的三角形为:

对于N = 2形成的三角形为:

例子:

方法:

下面是上述方法的实现:

C++
#include 
using namespace std;
// function to return the
// total no.of Triangles
int CountTriangles(int n)
{
    int curr = 1;
    int Tri_count = 0;
    for (int i = 1; i <= n; i++) {
        // For every subtriangle formed
        // there are possibilities of
        // generating (curr*3)+2
 
        Tri_count = (curr * 3) + 2;
        // Changing the curr value to Tri_count
        curr = Tri_count;
    }
    return Tri_count;
}
 
// driver code
int main()
{
    int n = 10;
    cout << CountTriangles(n);
    return 0;
}


Java
class Gfg {
    // Method to return the
    // total no.of Triangles
    public static int CountTriangles(int n)
    {
        int curr = 1;
        int Tri_count = 0;
        for (int i = 1; i <= n; i++) {
            // For every subtriangle formed
            // there are possibilities of
            // generating (curr*3)+2
 
            Tri_count = (curr * 3) + 2;
            // Changing the curr value to Tri_count
            curr = Tri_count;
        }
        return Tri_count;
    }
 
    // driver code
    public static void main(String[] args)
    {
        int n = 10;
        System.out.println(CountTriangles(n));
    }
}


Python
# Function to return the
# total no.of Triangles
def countTriangles(n):
     
    curr = 1
    Tri_count = 0
    for i in range(1, n + 1):
             
        # For every subtriangle formed
        # there are possibilities of
        # generating (curr * 3)+2
        Tri_count = (curr * 3) + 2
        # Changing the curr value to Tri_count
        curr = Tri_count
    return Tri_count
     
n = 10
print(countTriangles(n))


C#
using System;
 
class Gfg
{
    // Method to return the
    // total no.of Triangles
    public static int CountTriangles(int n)
    {
        int curr = 1;
        int Tri_count = 0;
        for (int i = 1; i <= n; i++)
        {
            // For every subtriangle formed
            // there are possibilities of
            // generating (curr*3)+2
            Tri_count = (curr * 3) + 2;
             
            // Changing the curr value to Tri_count
            curr = Tri_count;
        }
        return Tri_count;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 10;
        Console.WriteLine(CountTriangles(n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
118097