Find the sum of n terms of the series 12, 105, 1008, 10011, …
Given a positive integer n. Find the sum of the first n term of the series
12, 105, 1008, 10011, …..
Examples:
Input: n = 4
Output: 11136
Input: n = 7
Output: 11111187
Approach:
The sequence is formed by using the following pattern. For any value N-
The above solution can be derived following a series of steps:
Given Series-
12 + 105 + 1008 + 10011 +…….
10 + 2 + 100 + 5 + 1000 + 8 + 10000 + 11 +……..
(10 + 100 + 1000 + 10000+……) + (2 + 5 + 8 + 11+……) -(1)
The first term in the above equation is Geometric progression and the second term is Arithmetic progression.
G.P. =
where a is the first term a, r is the common ratio and n is the number of terms.
A.P. =
where a is the first term a, a is the common difference and n is the number of terms.
So after substituting values in equation of G.P. and A.P. and substituting corresponding equations in equation (1) we get,
So,
Illustration:
Input: n = 4
Output: 11136
Explanation:
This gives ans 11136.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll findSum(ll n)
{
ll x = 10 * ( pow (10, n) - 1) / 9;
ll y = n * (3 * n + 1) / 2;
return x + y;
}
int main()
{
ll n = 4;
cout << findSum(n);
return 0;
}
|
Java
class GFG
{
static int findSum( int n) {
int x = ( int )( 10 * (Math.pow( 10 , n) - 1 ) / 9 );
int y = n * ( 3 * n + 1 ) / 2 ;
return x + y;
}
public static void main(String args[]) {
int n = 4 ;
System.out.println(findSum(n));
}
}
|
Python3
def findSum(n):
x = 10 * (( 10 * * n) - 1 ) / 9
y = n * ( 3 * n + 1 ) / 2
return int (x + y)
n = 4
print (findSum(n))
|
C#
using System;
class GFG
{
static int findSum( int n) {
int x = ( int )(10 * (Math.Pow(10, n) - 1) / 9);
int y = n * (3 * n + 1) / 2;
return x + y;
}
public static void Main()
{
int n = 4;
Console.Write(findSum(n));
}
}
|
Javascript
<script>
function findSum(n) {
let x = 10 * (Math.pow(10, n) - 1) / 9;
let y = n * (3 * n + 1) / 2;
return Math.floor(x) + Math.floor(y);
}
let N = 4;
document.write(findSum(N));
</script>
|
Time Complexity: O(logN) since it is using pow function
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
16 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...