If inverse of a sequence follows rule of an A.P i.e, Arithmetic progression, then it is said to be in Harmonic Progression.In general, the terms in a harmonic progression can be denoted as : 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) …. 1/(a + nd).
As Nth term of AP is given as ( a + (n – 1)d) .Hence, Nth term of harmonic progression is reciprocal of Nth term of AP, which is : 1/(a + (n – 1)d)
where “a” is the 1st term of AP and “d” is the common difference.
We can use a for loop to find sum.
C++
#include <iostream>
using namespace std;
class gfg
{
public : double sum( int n)
{
double i, s = 0.0;
for (i = 1; i <= n; i++)
s = s + 1/i;
return s;
}
};
int main()
{
gfg g;
int n = 5;
cout << "Sum is " << g.sum(n);
return 0;
}
|
C
#include <stdio.h>
double sum( int n)
{
double i, s = 0.0;
for (i = 1; i <= n; i++)
s = s + 1/i;
return s;
}
int main()
{
int n = 5;
printf ( "Sum is %f" , sum(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
static double sum( int n)
{
double i, s = 0.0 ;
for (i = 1 ; i <= n; i++)
s = s + 1 /i;
return s;
}
public static void main(String args[])
{
int n = 5 ;
System.out.printf( "Sum is %f" , sum(n));
}
}
|
Python3
def sum (n):
i = 1
s = 0.0
for i in range ( 1 , n + 1 ):
s = s + 1 / i;
return s;
n = 5
print ( "Sum is" , round ( sum (n), 6 ))
|
C#
using System;
class GFG {
static float sum( int n)
{
double i, s = 0.0;
for (i = 1; i <= n; i++)
s = s + 1/i;
return ( float )s;
}
public static void Main()
{
int n = 5;
Console.WriteLine( "Sum is "
+ sum(n));
}
}
|
PHP
<?php
function sum( $n )
{
$i ;
$s = 0.0;
for ( $i = 1; $i <= $n ; $i ++)
$s = $s + 1 / $i ;
return $s ;
}
$n = 5;
echo ( "Sum is " );
echo (sum( $n ));
?>
|
Javascript
<script>
function sum(n)
{
var i, s = 0.0;
for (i = 1; i <= n; i++)
s = s + 1/i;
return s;
}
var n = 5;
document.write(sum(n).toFixed(5));
</script>
|
Output:
2.283333
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!