Centered heptagonal number
Last Updated :
19 May, 2022
Given a number n, the task is to find nth Centered heptagonal number.
Centered heptagonal number is centered figure number that represents a heptagon with dot in center and all other dot surrounding in heptagonal form. Nth centered heptagonal number can be calculated by using formula (7n2 – 7n + 2) / 2.
Examples :
Input : n = 2
Output : 8
Input : n = 7
Output : 148
Please refer this diagram for pictorial representation.
Below is the implementation :
C++
#include <bits/stdc++.h>
using namespace std;
int centered_heptagonal_num( long int n)
{
return (7 * n * n - 7 * n + 2) / 2;
}
int main()
{
long int n = 5;
cout << n << "th Centered heptagonal number : " ;
cout << centered_heptagonal_num(n);
return 0;
}
|
C
#include <stdio.h>
int centered_heptagonal_num( long int n)
{
return (7 * n * n - 7 * n + 2) / 2;
}
int main()
{
long int n = 5;
printf ( "%ldth Centered heptagonal number : " ,n);
printf ( "%d" ,centered_heptagonal_num(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static long centered_heptagonal_num( long n)
{
return ( 7 * n * n - 7 * n + 2 ) / 2 ;
}
public static void main (String[] args)
{
long n = 5 ;
System.out.println( n + "th Centered "
+ "heptagonal number : "
+ centered_heptagonal_num(n));
}
}
|
Python3
def centered_heptagonal_num(n):
return ( 7 * n * n - 7 * n + 2 ) / / 2
n = 5
print ( "%sth Centered heptagonal number : " % n,
centered_heptagonal_num(n))
|
C#
using System;
class GFG {
static long centered_heptagonal_num( long n)
{
return (7 * n * n - 7 * n + 2) / 2;
}
public static void Main ()
{
long n = 5;
Console.WriteLine( n + "th Centered "
+ "heptagonal number : "
+ centered_heptagonal_num(n));
}
}
|
PHP
<?php
function centered_heptagonal_num( $n )
{
return (7 * $n * $n - 7 *
$n + 2) / 2;
}
$n = 5;
echo $n , "th Centered heptagonal number : " ;
echo centered_heptagonal_num( $n );
?>
|
Javascript
<script>
function centered_heptagonal_num(n)
{
return parseInt((7 * n * n - 7 * n + 2) / 2);
}
let n = 5;
document.write(n + "th Centered heptagonal number : " );
document.write(centered_heptagonal_num(n));
</script>
|
Output :
5th Centered heptagonal number : 71
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...