Program to print the Sum of series -1 + 2 + 11 + 26 + 47 +…..
Given a number N, the task is to find the sum of first N number of series:
-1, 2, 11, 26, 47, 74, …..
Examples:
Input: N = 3
Output: 12
Explanation:
Sum = (N * (N + 1) * (2 * N - 5) + 4 * N) / 2
= (3 * (3 + 1) * (2 * 3 - 5) + 4 * 3) / 2
= 12
Input: N = 9
Output: 603
Approach:
The Nth term of the given series can be generalised as:
Nth term of the series
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int findSum( int N)
{
return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2;
}
int main()
{
int N = 3;
cout << findSum(N) << endl;
return 0;
}
|
Java
import java.util.*;
class solution
{
static int findSum( int N)
{
return (N * (N + 1 ) * ( 2 * N - 5 ) + 4 * N) / 2 ;
}
public static void main(String arr[])
{
int N = 3 ;
System.out.println(findSum(N));
}
}
|
Python3
def findSum(N):
return ((N * (N + 1 ) *
( 2 * N - 5 ) + 4 * N) / 2 )
if __name__ = = '__main__' :
N = 3
print (findSum(N))
|
C#
using System;
class GFG
{
static int findSum( int N)
{
return (N * (N + 1) *
(2 * N - 5) + 4 * N) / 2;
}
static public void Main ()
{
int N = 3;
Console.Write(findSum(N));
}
}
|
PHP
<?php
function findSum( $N )
{
return ( $N * ( $N + 1) *
(2 * $N - 5) + 4 * $N ) / 2;
}
$N = 3;
echo findSum( $N ) . "\n" ;
?>
|
Javascript
<script>
function findSum(N)
{
return (N * (N + 1) * (2 * N - 5) + 4 * N) / 2;
}
var N = 3;
document.write(findSum(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
31 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...