Sum of the series 5+55+555+.. up to n terms
Find the sum up to n terms of the sequence: 5 + 55 + 555 + … up to n.
Examples :
Input : 2
Output: 60
Input : 3
Output: 595
Approach:The above problem can be solved using the following formula:
Sum = 5 + 55 + 555 + …. n terms.
= 5/9[9 + 99 + 999 + …. n terms]
= 5/9[(10 – 1) + (100 – 1) + (1000 – 1) + … n terms]
= 5/9[10 + 100 + 1000 ….. – (1 + 1 + … 1)]
= 5/9[10(10n – 1)/(10 – 1) + (1 + 1 + … n times))
= 50/81(10n – 1) – 5n/9
Below is the Implementation to find the sum of given series:
C++
#include <bits/stdc++.h>
using namespace std;
int sumOfSeries( int n)
{
return 0.6172 *
( pow (10, n) - 1) -
0.55 * n;
}
int main()
{
int n = 2;
cout << sumOfSeries(n);
return 0;
}
|
Java
class GFG
{
static int sumOfSeries( int n)
{
return ( int ) ( 0.6172 *
(Math.pow( 10 , n) - 1 ) -
0.55 * n);
}
public static void main(String []args)
{
int n = 2 ;
System.out.println(sumOfSeries(n));
}
}
|
Python3
def sumOfSeries(n):
return ( int ) ( 0.6172 *
( pow ( 10 , n) - 1 ) -
0.55 * n)
n = 2
print (sumOfSeries(n))
|
C#
using System;
class GFG
{
static int sumOfSeries( int n)
{
return ( int )(0.6172 *
(Math.Pow(10, n) - 1) -
0.55 * n);
}
public static void Main()
{
int n = 2;
Console.Write(sumOfSeries(n));
}
}
|
PHP
<?php
function sumOfSeries( $n )
{
return (int)(0.6172 *
(pow(10, $n ) - 1) -
0.55 * $n );
}
$n = 2;
echo (sumOfSeries( $n ));
?>
|
Javascript
<script>
function sumOfSeries(n) {
return parseInt( (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n));
}
var n = 2;
document.write(sumOfSeries(n));
</script>
|
Output :
60
Time complexity: O(log n) since using the inbuilt power function.
Auxiliary Space: O(1)
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...