Given a number n, the task is to find n-th octahedral number.
An octahedral number belongs to a figurate number and it is the number of spheres in an octahedron built from closely packed spheres. First, a few octahedral numbers (where n = 0, 1, 2, 3…….) are 0, 1, 6, 19, and so on.
Examples :
Input: 4
Output: 44
Input: 8
Output: 344
Formula for nth octahedral number:
n * (2n2+1) / 3
C++
#include <bits/stdc++.h>
using namespace std;
int octahedral_num( int n)
{
return n * (2 * n * n + 1) / 3;
}
int main()
{
int n = 5;
cout << n << "th Octahedral number: " ;
cout << octahedral_num(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int octahedral_num( int n)
{
return n * ( 2 * n * n + 1 ) / 3 ;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.print(n + "th Octahedral"
+ " number: " );
System.out.println(octahedral_num(n));
}
}
|
Python3
def octahedral_num(n) :
return n * ( 2 * n * n + 1 ) / / 3
if __name__ = = '__main__' :
n = 5
print (n, "th Octahedral number: "
, octahedral_num(n))
|
C#
using System;
class GFG
{
static int octahedral_num( int n)
{
return n * (2 * n *
n + 1) / 3;
}
static public void Main ()
{
int n = 5;
Console.Write(n + "th Octahedral"
+ " number: " );
Console.WriteLine(octahedral_num(n));
}
}
|
PHP
<?php
function octahedral_num( $n )
{
return $n * (2 * $n * $n + 1) / 3;
}
$n = 5;
echo $n , "th Octahedral number: " ;
echo octahedral_num( $n );
?>
|
Javascript
<script>
function octahedral_num( n)
{
return n * (2 * n * n + 1) / 3;
}
let n = 5;
document.write( n+ "th Octahedral number: " );
document.write(octahedral_num(n));
</script>
|
Output
5th Octahedral number: 85
Time Complexity: O(1) because constant operations are being performed
Auxiliary Space: O(1)
Reference: https://en.wikipedia.org/wiki/Octahedral_number
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Dec, 2022
Like Article
Save Article