Centered Octagonal Number
Last Updated :
29 Mar, 2023
Given a number n, find the nth centered octagonal number.
A centered octagonal number represents an octagon with a dot in the center and others dots surrounding the center dot in the successive octagonal layer.
Examples :
Input : 2
Output : 9
Input : 5
Output : 81
Centered Octagonal n-th Number is given by :
Basic Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cen_octagonalnum( long int n)
{
return (4 * n * n - 4 * n + 1);
}
int main()
{
long int n = 6;
cout << n << "th centered"
<< " octagonal number : " ;
cout << cen_octagonalnum(n);
cout << endl;
n = 11;
cout << n << "th centered"
<< " octagonal number : " ;
cout << cen_octagonalnum(n);
return 0;
}
|
C
#include <stdio.h>
int cen_octagonalnum( long int n)
{
return (4 * n * n - 4 * n + 1);
}
int main()
{
long int n = 6;
printf ( "%ldth centered octagonal number : " ,n);
printf ( "%d\n" ,cen_octagonalnum(n));
n = 11;
printf ( "%ldth centered octagonal number : " ,n);
printf ( "%d\n" ,cen_octagonalnum(n));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int centeredoctagonalNumber( int n)
{
return 4 * n * (n - 1 ) + 1 ;
}
public static void main(String args[])
{
int n = 6 ;
System.out.print(n + "th centered " +
"octagonal number: " );
System.out.println(
centeredoctagonalNumber(n));
n = 11 ;
System.out.print(n + "th centered " +
"octagonal number: " );
System.out.println(
centeredoctagonalNumber(n));
}
}
|
Python3
def cen_octagonalnum(n) :
return ( 4 * n * n -
4 * n + 1 )
if __name__ = = '__main__' :
n = 6
print (n, "th Centered" ,
"octagonal number: " ,
cen_octagonalnum(n))
n = 11
print (n, "th Centered" ,
"octagonal number: " ,
cen_octagonalnum(n))
|
C#
using System;
public class GFG{
static long cen_octagonalnum( long n)
{
return (4 * n * n - 4 * n + 1);
}
static public void Main ()
{
long n = 6;
Console.WriteLine(n + "th centered"
+ " octagonal number : "
+ cen_octagonalnum(n));
n = 11;
Console.WriteLine(n + "th centered"
+ " octagonal number : "
+ cen_octagonalnum(n));
}
}
|
PHP
<?php
function cen_octagonalnum( $n )
{
return (4 * $n * $n -
4 * $n + 1);
}
$n = 6;
echo $n , "th centered" ,
" octagonal number : " ;
echo cen_octagonalnum( $n );
echo "\n" ;
$n = 11;
echo $n , "th centered" ,
" octagonal number : " ;
echo cen_octagonalnum( $n );
?>
|
Javascript
<script>
function centeredoctagonalNumber(n)
{
return 4 * n * (n - 1) + 1;
}
var n = 6;
document.write(n + "th centered " +
"octagonal number: " );
document.write(centeredoctagonalNumber(n) + "<br>" );
n = 11;
document.write(n + "th centered " +
"octagonal number: " );
document.write(centeredoctagonalNumber(n));
</script>
|
Output
6th centered octagonal number : 121
11th centered octagonal number : 441
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...