Find the sum of the first N Centered Pentagonal Number
Last Updated :
16 Jul, 2021
Given a number N, the task is to find the sum of first N Centered Pentagonal Numbers.
The first few Centered Pentagonal Number are 1, 6, 16, 31, 51, 76, 106 …
Examples:
Input: N = 3
Output: 23
Explanation:
1, 6 and 16 are the first three
Centered Pentagonal number.
Input: N = 5
Output: 105
Approach: The idea is to first create a function which would help us to find the centered pentagonal number in a constant time. The implementation of this function has already been discussed in this article. The following steps are followed after creating this function:
- Run a loop starting from 1 to N, to find ith Centered Pentagonal number.
- Add all the above calculated Centered Pentagonal numbers.
- Then, display the sum of N Centered Pentagonal numbers.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int Centered_Pentagonal_num( int n)
{
return (5 * n * n - 5 * n + 2) / 2;
}
int sum_Centered_Pentagonal_num( int n)
{
int summ = 0;
for ( int i = 1; i < n + 1; i++)
{
summ += Centered_Pentagonal_num(i);
}
return summ;
}
int main()
{
int n = 5;
cout << (sum_Centered_Pentagonal_num(n));
return 0;
}
|
Java
class GFG{
static int Centered_Pentagonal_num( int n)
{
return ( 5 * n * n - 5 * n + 2 ) / 2 ;
}
static int sum_Centered_Pentagonal_num( int n)
{
int summ = 0 ;
for ( int i = 1 ; i < n + 1 ; i++)
{
summ += Centered_Pentagonal_num(i);
}
return summ;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.print((sum_Centered_Pentagonal_num(n)));
}
}
|
Python3
def Centered_Pentagonal_num(n):
return ( 5 * n * n -
5 * n + 2 ) / / 2
def sum_Centered_Pentagonal_num(n) :
summ = 0
for i in range ( 1 , n + 1 ):
summ + = Centered_Pentagonal_num(i)
return summ
if __name__ = = '__main__' :
n = 5
print (sum_Centered_Pentagonal_num(n))
|
C#
using System;
class GFG{
static int Centered_Pentagonal_num( int n)
{
return (5 * n * n - 5 * n + 2) / 2;
}
static int sum_Centered_Pentagonal_num( int n)
{
int summ = 0;
for ( int i = 1; i < n + 1; i++)
{
summ += Centered_Pentagonal_num(i);
}
return summ;
}
public static void Main(String[] args)
{
int n = 5;
Console.Write((sum_Centered_Pentagonal_num(n)));
}
}
|
Javascript
<script>
function Centered_Pentagonal_num(n)
{
return (5 * n * n - 5 * n + 2) / 2;
}
function sum_Centered_Pentagonal_num(n)
{
let summ = 0;
for (let i = 1; i < n + 1; i++)
{
summ += Centered_Pentagonal_num(i);
}
return summ;
}
let n = 5;
document.write(sum_Centered_Pentagonal_num(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...