Triangular Matchstick Number
Given a number X which represents the floor of a matchstick pyramid, write a program to print the total number of matchstick required to form pyramid of matchsticks of x floors.
Examples:
Input : X = 1
Output : 3
Input : X = 2
Output : 9
This is mainly an extension of triangular numbers. For a number X, the matchstick required will be three times of X-th triangular numbers, i.e., (3*X*(X+1))/2
C++
#include <bits/stdc++.h>
using namespace std;
int numberOfSticks( int x)
{
return (3 * x * (x + 1)) / 2;
}
int main()
{
cout<<numberOfSticks(7);
return 0;
}
|
Java
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
def numberOfSticks(x):
return ( 3 * x * (x + 1 )) / 2
print ( int (numberOfSticks( 7 )))
|
C#
using System;
class GFG
{
static int numberOfSticks( int x)
{
return (3 * x * (x + 1)) / 2;
}
public static void Main()
{
Console.Write(numberOfSticks(7));
}
}
|
PHP
<?php
function numberOfSticks( $x )
{
return (3 * $x * ( $x + 1)) / 2;
}
echo (numberOfSticks(7));
?>
|
Javascript
<script>
function numberOfSticks( x)
{
return (3 * x * (x + 1)) / 2;
}
document.write(numberOfSticks(7));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
22 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...