You have been given a series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n, find out the sum of the series till nth term.
Input : n = 3
Output : 1.28704
Explanation : 1 + 1/2^2 + 1/3^3
Input : n = 5
Output : 1.29126
Explanation : 1 + 1/2^2 + 1/3^3 + 1/4^4 + 1/5^5
We use power function to compute power.
C++
#include <bits/stdc++.h>
using namespace std;
double Series( int n)
{
int i;
double sums = 0.0, ser;
for (i = 1; i <= n; ++i)
{
ser = 1 / pow (i, i);
sums += ser;
}
return sums;
}
int main()
{
int n = 3;
double res = Series(n);
cout << res;
return 0;
}
|
C
#include <math.h>
#include <stdio.h>
double Series( int n)
{
int i;
double sums = 0.0, ser;
for (i = 1; i <= n; ++i) {
ser = 1 / pow (i, i);
sums += ser;
}
return sums;
}
int main()
{
int n = 3;
double res = Series(n);
printf ( "%.5f" , res);
return 0;
}
|
Java
import java.io.*;
class Maths {
static double Series( int n)
{
int i;
double sums = 0.0 , ser;
for (i = 1 ; i <= n; ++i) {
ser = 1 / Math.pow(i, i);
sums += ser;
}
return sums;
}
public static void main(String[] args)
{
int n = 3 ;
double res = Series(n);
res = Math.round(res * 100000.0 ) / 100000.0 ;
System.out.println(res);
}
}
|
Python3
def Series(n):
sums = 0.0
for i in range ( 1 , n + 1 ):
ser = 1 / (i * * i)
sums + = ser
return sums
n = 3
res = round (Series(n), 5 )
print (res)
|
C#
using System;
class Maths {
static double Series( int n)
{
int i;
double sums = 0.0, ser;
for (i = 1; i <= n; ++i) {
ser = 1 / Math.Pow(i, i);
sums += ser;
}
return sums;
}
public static void Main()
{
int n = 3;
double res = Series(n);
res = Math.Round(res * 100000.0) / 100000.0;
Console.Write(res);
}
}
|
PHP
<?php
function Series( $n )
{
$i ;
$sums = 0.0;
$ser ;
for ( $i = 1; $i <= $n ; ++ $i )
{
$ser = 1 / pow( $i , $i );
$sums += $ser ;
}
return $sums ;
}
$n = 3;
$res = Series( $n );
echo $res ;
?>
|
Javascript
<script>
function Series(n)
{
let sums = 0.0;
for (let i = 1; i < n + 1; i++)
{
ser = 1 / Math.pow(i, i);
sums += ser;
}
return sums;
}
let n = 3;
let res = Math.round(Series(n) * 100000) / 100000;
document.write(res);
</script>
|
Time Complexity: O(nlogn) since using inbuilt pow function in loop
Auxiliary Space: O(1)
Contact Us