Find the sum of the first N Centered Octagonal Number
Last Updated :
01 Dec, 2022
Given a number N, the task is to find the sum of the first N Centered Octagonal Numbers.
The first few Centered Octagonal numbers are 1, 9, 25, 49, 81, 121, 169, 225, 289, 361 …
Examples:
Input: N = 3
Output: 35
Explanation:
1, 9 and 25 are the first three Centered Octagonal numbers.
Input: N = 5
Output: 165
Approach:
- Initially, we need to create a function that will help us to calculate the Nth centered octagonal numbers.
- Now, run a loop starting from 1 to N, to find ith centered octagonal numbers.
- Add all the above calculated centered octagonal numbers.
- Finally, display the sum of the first N-centered octagonal numbers.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int center_Octagonal_num( int n)
{
return (4 * n * n - 4 * n + 1);
}
int sum_center_Octagonal_num( int n)
{
int summ = 0;
for ( int i = 1; i < n + 1; i++)
{
summ += center_Octagonal_num(i);
}
return summ;
}
int main()
{
int n = 5;
cout << (sum_center_Octagonal_num(n));
return 0;
}
|
Java
class GFG {
static int center_Octagonal_num( int n)
{
return ( 4 * n * n - 4 * n + 1 );
}
static int sum_center_Octagonal_num( int n)
{
int summ = 0 ;
for ( int i = 1 ; i < n + 1 ; i++)
{
summ += center_Octagonal_num(i);
}
return summ;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println(sum_center_Octagonal_num(n));
}
}
|
Python3
def center_Octagonal_num(n):
return ( 4 * n * n - 4 * n + 1 )
def sum_center_Octagonal_num(n) :
summ = 0
for i in range ( 1 , n + 1 ):
summ + = center_Octagonal_num(i)
return summ
if __name__ = = '__main__' :
n = 5
print (sum_center_Octagonal_num(n))
|
C#
using System;
class GFG{
static int center_Octagonal_num( int n)
{
return (4 * n * n - 4 * n + 1);
}
static int sum_center_Octagonal_num( int n)
{
int summ = 0;
for ( int i = 1; i < n + 1; i++)
{
summ += center_Octagonal_num(i);
}
return summ;
}
public static void Main()
{
int n = 5;
Console.WriteLine(sum_center_Octagonal_num(n));
}
}
|
Javascript
<script>
function center_Octagonal_num(n)
{
return (4 * n * n - 4 * n + 1);
}
function sum_center_Octagonal_num(n)
{
let summ = 0;
for (let i = 1; i < n + 1; i++)
{
summ += center_Octagonal_num(i);
}
return summ;
}
let n = 5;
document.write(sum_center_Octagonal_num(n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...