Sum of the sequence 2, 22, 222, ………
Find the sum of the following sequence : 2, 22, 222, ……… to n terms.
Examples :
Input : 2
Output: 23.99868
Input : 3
Output: 245.98647
A simple solution is to compute terms one by one and add to the result.
The above problem can be efficiently solved using the following formula:
C++14
#include <bits/stdc++.h>
using namespace std;
float sumOfSeries( int n)
{
return 0.02469 * (10*( pow (10, n) - 1)- (9 * n));
}
int main()
{
int n = 3;
cout << sumOfSeries(n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static double sumOfSeries( int n)
{
return 0.02469 * (( 10 *Math.pow( 10 , n)
- 1 ) - ( 9 * n));
}
public static void main(String[] args)
{
int n = 3 ;
System.out.println(sumOfSeries(n));
}
}
|
Python3
import math
def sumOfSeries( n ):
return 0.02469 * (( 10 * math. pow ( 10 , n) - 1 ) - ( 9 * n))
n = 3
print ( sumOfSeries(n))
|
C#
using System;
class GFG {
static double sumOfSeries( int n)
{
return 0.02469 * ((10*Math.Pow(10, n)
- 1) - (9 * n));
}
public static void Main()
{
int n = 3;
Console.Write(sumOfSeries(n));
}
}
|
PHP
<?php
function sumOfSeries( $n )
{
return 0.02469 * ((10*pow(10, $n ) -
1 )- (9 * $n ));
}
$n = 3;
echo (sumOfSeries( $n ));
?>
|
Javascript
<script>
function sumOfSeries(n)
{
return 0.0246 * ((10*Math.pow(10, n)
- 1) - (9 * n));
}
let n = 3;
document.write(sumOfSeries(n));
</script>
|
Time complexity: O(log n) since using inbuilt power function.
Auxiliary Space: O(1)
Last Updated :
25 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...