Find sum of the series 1+22+333+4444+…… upto n terms
Last Updated :
25 May, 2022
Given a number N. The task is to find the sum of the below series up to N-th term:
1 + 22 + 333 + 4444 + …up to n terms
Examples:
Input: N = 3
Output: 356
Input: N = 10
Output: 12208504795
Approach:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <math.h>
using namespace std;
int findSum( int n)
{
return ( pow (10, n + 1) * (9 * n - 1) + 10) /
pow (9, 3) - n * (n + 1) / 18;
}
int main()
{
int n = 3;
cout << findSum(n);
return 0;
}
|
Java
import java.util.*;
class solution
{
static int calculateSum( int n)
{
return (( int )Math.pow( 10 , n + 1 ) * ( 9 * n - 1 ) + 10 ) /
( int )Math.pow( 9 , 3 ) - n * (n + 1 ) / 18 ;
}
public static void main(String ar[])
{
int n= 3 ;
System.out.println( "Sum= " + calculateSum(n));
}
}
|
Python 3
def solve_sum(n):
return ( pow ( 10 , n + 1 ) * ( 9 * n - 1 ) + 10 ) / pow ( 9 , 3 ) - n * (n + 1 ) / 18
n = 3
print ( int (solve_sum(n)))
|
C#
using System;
class solution
{
static int calculateSum( int n)
{
return (( int )Math.Pow(10, n + 1) * (9 * n - 1) + 10) /
( int )Math.Pow(9, 3) - n * (n + 1) / 18;
}
public static void Main()
{
int n=3;
Console.WriteLine( "Sum= " + calculateSum(n));
}
}
|
PHP
<?php
function findSum( $n )
{
return (pow(10, $n + 1) *
(9 * $n - 1) + 10) /
pow(9, 3) - $n * ( $n + 1) / 18;
}
$n = 3;
echo findSum( $n );
?>
|
Javascript
<script>
function calculateSum( n)
{
return (parseInt(Math.pow(10, n + 1)) * (9 * n - 1) + 10) /
parseInt(Math.pow(9, 3)) - n * (n + 1) / 18;
}
let n = 3;
document.write( "Sum= " + calculateSum(n));
</script>
|
Time Complexity: O(logn), where n represents the given integer, as we have used pow function.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...