📜  计算形成高度为 N 的纸牌屋所需的三角形

📅  最后修改于: 2021-10-23 08:34:33             🧑  作者: Mango

给定一个数字N ,任务是计算形成N级纸牌屋所需的三角形数量。

例子:

方法:形成N层纸牌屋所需的三角形数量可以通过以下公式计算:

插图:

下面是上述方法的实现:

CPP
// C++ implementation of the
// above approach
 
#include 
using namespace std;
 
// Function to find the
// number of triangles
int noOfTriangles(int n)
{
    return floor(n * (n + 2)
                 * (2 * n + 1) / 8);
}
 
// Driver Code
int main()
{
    int n = 3;
    // Function call
    cout << noOfTriangles(n) << endl;
    return 0;
}


Java
// Java implementation of the
// above approach
 
import java.lang.*;
 
class GFG {
 
    // Function to find number of triangles
    public static int noOfTriangles(int n)
    {
        return (n * (n + 2) * (2 * n + 1) / 8);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int n = 3;
        // Function call
        System.out.print(noOfTriangles(n));
    }
}


Python3
# Python3 implementation of
# the above approach
 
# Function to find required
# number of triangles
def noOfTriangles(n):
    return n * (n + 2) * (2 * n + 1) // 8
 
 
# Driver Code
n = 3
 
# Function call
print(noOfTriangles(n))


C#
// C# implementation of the
// above approach
using System;
 
class GFG {
    // Function to find number of triangles
    public static int noOfTriangles(int n)
    {
        return (n * (n + 2) * (2 * n + 1) / 8);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int n = 3;
        Console.Write(noOfTriangles(n));
    }
}


Javascript


输出:
13

时间复杂度: O(1)
辅助空间: O(1)