Related Articles

Related Articles

Triangular Matchstick Number
  • Difficulty Level : Easy
  • Last Updated : 31 Oct, 2018

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find X-th triangular
// matchstick number
  
#include <bits/stdc++.h>
using namespace std;
  
int numberOfSticks(int x)
{
    return (3 * x * (x + 1)) / 2;
}
  
int main() 
{
    cout<<numberOfSticks(7);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find X-th triangular
# matchstick number
  
def numberOfSticks(x):
    return (3 * x * (x + 1)) / 2
      
# main()
print(int(numberOfSticks(7)))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find
// X-th triangular
// matchstick number
  
function numberOfSticks($x)
{
    return (3 * $x * ($x + 1)) / 2;
}
  
// Driver code
echo(numberOfSticks(7));
  
// This code is contributed by Ajit.
?>

chevron_right


Output:

84

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :