给定一个数字N ,任务是计算形成N级纸牌屋所需的三角形数量。
例子:
Input: N = 3
Output: 13
Explanation:
From the above image, the following observations can be made:
Count of triangles of unit 1 = 9 (6 non-inverted triangles and 3 inverted triangles)
Count of triangles of unit 2 = 3
Count of triangles of unit 3 = 1
Therefore, total number of triangles = 6 + 3 + 3 + 1 = 13
Input: N = 2
Output: 5
方法:形成N层纸牌屋所需的三角形数量可以通过以下公式计算:
插图:
For N = 3
Count of triangles = 3 * (3 + 2) * (6 + 1) / 8 = 13
For N = 2
Count of triangles = 2 * (2 + 2) * (4+ 1) / 8 = 5
下面是上述方法的实现:
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)