A number is termed as a tetrahedral number if it can be represented as a pyramid with a triangular base and three sides, called a tetrahedron. The nth tetrahedral number is the sum of the first n triangular numbers.
The first ten tetrahedral numbers are:
1, 4, 10, 20, 35, 56, 84, 120, 165, 220, …

Formula for nth tetrahedral number:
Tn = (n * (n + 1) * (n + 2)) / 6
Proof:
The proof uses the fact that the nth tetrahedral
number is given by,
Trin = (n * (n + 1)) / 2
It proceeds by induction.
Base Case
T1 = 1 = 1 * 2 * 3 / 6
Inductive Step
Tn+1 = Tn + Trin+1
Tn+1 = [((n * (n + 1) * (n + 2)) / 6] + [((n + 1) * (n + 2)) / 2]
Tn+1 = (n * (n + 1) * (n + 2)) / 6
Below is the implementation of above idea :
C++
#include <iostream>
using namespace std;
int tetrahedralNumber( int n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
int main()
{
int n = 5;
cout << tetrahedralNumber(n) << endl;
return 0;
}
|
Java
class GFG {
static int tetrahedralNumber( int n)
{
return (n * (n + 1 ) * (n + 2 )) / 6 ;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println(tetrahedralNumber(n));
}
}
|
Python
def tetrahedralNumber(n):
return (n * (n + 1 ) * (n + 2 )) / 6
n = 5
print (tetrahedralNumber(n))
|
C#
using System;
public class GFG{
static int tetrahedralNumber( int n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
static public void Main ()
{
int n = 5;
Console.WriteLine(tetrahedralNumber(n));
}
}
|
PHP
<?php
function tetrahedralNumber( $n )
{
return ( $n * ( $n + 1) * ( $n + 2)) / 6;
}
$n = 5;
echo tetrahedralNumber( $n );
?>
|
Javascript
<script>
function tetrahedralNumber(n)
{
return (n * (n + 1) * (n + 2)) / 6;
}
let n = 5;
document.write(tetrahedralNumber(n));
</script>
|
Output:
35
Time Complexity: O(1).
Space complexity: O(1) since using constant variables