Find the sum of N terms of the series 0.1, 0.11, 0.111, …
Given a positive integer, N. Find the sum of the first N term of the series-
0.1, 0.11, 0.111, 0.1111, ….till N terms
Examples:
Input: N = 6
Output: 0.654321
Input: N = 1
Output: 0.1
Approach:
1st term = 0.1
2nd term = 0.11
3rd term = 0.111
4th term = 0.1111
.
.
Nth term = 1/9(1 – (1/10) ^ N)
The sequence is formed by using the following pattern. For any value N-
Derivation:
The following series of steps can be used to derive the formula to find the sum of N terms-
The series 0.1, 0.11, 0.111, …till N terms can be written as
-(1)
The series is in G.P. with
First term a = 0.1 = 10-1
Common Ratio r = 10-1
Sum of G.P. for r<1 can be expressed as-
Substituting the values of a and r in the equation-
-(2)
Substituting the equation (2) in (1), we get-
Illustration:
Input: N = 6
Output: 0.654321
Explanation:
Below is the implementation of the above approach-
C++
#include <bits/stdc++.h>
using namespace std;
double findSum( int N)
{
int a = pow (10, N);
return ( double )(N * 9 * a - a + 1)
/ (81 * a);
}
int main()
{
int N = 6;
cout << findSum(N);
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static double findSum( double N)
{
double a = Math.pow( 10 , N);
return ( double )(N * 9 * a - a + 1 )
/ ( 81 * a);
}
public static void main (String[] args) {
double N = 6 ;
System.out.print(findSum(N));
}
}
|
Python3
def findSum(N):
a = pow ( 10 , N)
return (N * 9 * a - a + 1 ) / ( 81 * a)
if __name__ = = "__main__" :
N = 6
print (findSum(N))
|
C#
using System;
class GFG
{
static double findSum( int N)
{
int a = ( int )Math.Pow(10, N);
return ( double )(N * 9 * a - a + 1)
/ (81 * a);
}
public static void Main()
{
int N = 6;
Console.Write(findSum(N));
}
}
|
Javascript
<script>
function findSum(N) {
let a = Math.pow(10, N);
return (N * 9 * a - a + 1)
/ (81 * a);
}
let N = 6;
document.write(findSum(N));
</script>
|
Time Complexity: O(logN) because it is using inbuilt pow function
Auxiliary Space: O(1)
Last Updated :
16 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...