Open In App

Count triangles required to form a House of Cards of height N

Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to count the number of triangles required to form a House of Cards of N levels.


Examples: 

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

Approach: The required number of triangles required to form a House of Cards of N levelscan be calculated by the formula:

T(n) = \left\lfloor\frac{n (n+2) (2n+1)} 8\right\rfloor

Illustration:

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


Below is the implementation of the above approach:

CPP

// C++ implementation of the
// above approach
 
#include <bits/stdc++.h>
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

<script>
 
// Javascript implementation of the
// above approach
 
// Function to find the
// number of triangles
function noOfTriangles(n)
{
    return Math.floor(n * (n + 2)
                 * (2 * n + 1) / 8);
}
 
// Driver Code
var n = 3;
// Function call
document.write(noOfTriangles(n));
 
</script>

                    

Output: 
13

 

Time Complexity: O(1)
Auxiliary Space: O(1)
 



Last Updated : 17 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads