Program to print the series 2, 15, 41, 80, 132, 197… till N terms
Given a number N, the task is to print the first N terms of the following series:
2 15 41 80 132 197 275 366 470 587…
Examples:
Input: N = 7
Output: 2 15 41 80 132 197 275
Input: N = 3
Output: 2 15 41
Approach: From the given series we can find the formula for Nth term:
1st term = 2
2nd term = 15 = 13 * 1 + 2
3rd term = 41 = 13 * 2 + 15 = 13 * 3 + 2
4th term = 80 = 13 * 3 + 41 = 13 * 6 + 2
5th term = 132 = 13 * 4 + 80 = 13 * 10 + 2
.
.
Nth term = (13 * N * (N – 1)) / 2 + 2
Therefore:
Nth term of the series
Then iterate over numbers in the range [1, N] to find all the terms using the above formula and print them.
Below is the implementation of above approach:
C++
#include "bits/stdc++.h"
using namespace std;
void printSeries( int N)
{
int ith_term = 0;
for ( int i = 1; i <= N; i++) {
ith_term = (13 * i * (i - 1)) / 2 + 2;
cout << ith_term << ", " ;
}
}
int main()
{
int N = 7;
printSeries(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printSeries( int N)
{
int ith_term = 0 ;
for ( int i = 1 ; i <= N; i++)
{
ith_term = ( 13 * i * (i - 1 )) / 2 + 2 ;
System.out.print(ith_term + ", " );
}
}
public static void main(String[] args)
{
int N = 7 ;
printSeries(N);
}
}
|
Python3
def printSeries(N):
ith_term = 0 ;
for i in range ( 1 , N + 1 ):
ith_term = ( 13 * i * (i - 1 )) / 2 + 2 ;
print ( int (ith_term), ", " , end = "");
if __name__ = = '__main__' :
N = 7 ;
printSeries(N);
|
C#
using System;
class GFG{
static void printSeries( int N)
{
int ith_term = 0;
for ( int i = 1; i <= N; i++)
{
ith_term = (13 * i * (i - 1)) / 2 + 2;
Console.Write(ith_term + ", " );
}
}
public static void Main(String[] args)
{
int N = 7;
printSeries(N);
}
}
|
Javascript
<script>
function printSeries( N)
{
let ith_term = 0;
for (let i = 1; i <= N; i++)
{
ith_term = (13 * i * (i - 1)) / 2 + 2;
document.write( ith_term + ", " );
}
}
let N = 7;
printSeries(N);
</script>
|
Output: 2, 15, 41, 80, 132, 197, 275,
Time complexity: O(n) because using a for loop
Auxiliary Space: O(1)
Last Updated :
03 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...