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

📅  最后修改于: 2021-04-24 21:51:38             🧑  作者: 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)