给定一个代表火柴金字塔的地板的数字X,编写一个程序以打印形成x层火柴金字塔的所需的火柴总数。
例子:
Input : X = 1
Output : 3
Input : X = 2
Output : 9
这主要是三角数的扩展。对于数字X,所需的火柴将是第X个三角数的三倍,即(3 * X *(X + 1))/ 2
C++
// C++ program to find X-th triangular
// matchstick number
#include
using namespace std;
int numberOfSticks(int x)
{
return (3 * x * (x + 1)) / 2;
}
int main()
{
cout<
Java
// Java program to find X-th triangular
// matchstick number
public class TriangularPyramidNumber {
public static int numberOfSticks(int x)
{
return (3 * x * (x + 1)) / 2;
}
public static void main(String[] args)
{
System.out.println(numberOfSticks(7));
}
}
Python3
# Python program to find X-th triangular
# matchstick number
def numberOfSticks(x):
return (3 * x * (x + 1)) / 2
# main()
print(int(numberOfSticks(7)))
C#
// C# program to find X-th triangular
// matchstick number
using System;
class GFG
{
// Function to ind missing number
static int numberOfSticks(int x)
{
return (3 * x * (x + 1)) / 2;
}
public static void Main()
{
Console.Write(numberOfSticks(7));
}
}
// This code is contributed by _omg
PHP
Javascript
输出:
84