Monday, June 29, 2020

Write a Python program to calculate the harmonic sum of n-1.

 Note: The harmonic sum is the sum of reciprocals of the positive integers.  Example: harmonic series
def harmonic_sum(n): if n < 2: return 1 else: return 1 / n + (harmonic_sum(n - 1)) print(harmonic_sum(7)) print(harmonic_sum(4))

Explanation:
harmonic_sum(7)=1/7+harmonic_sum(6)
harmonic_sum(7)=1/7+1/6+harmonic_sum(5)
harmonic_sum(7)=1/7+1/6+1/5+harmonic_sum(4)
harmonic_sum(7)=1/7+1/6+1/5+1/4+harmonic_sum(3)
harmonic_sum(7)=1/7+1/6+1/5+1/3+harmonic_sum(2)
harmonic_sum(7)=1/7+1/6+1/5+1/3+1/2+harmonic_sum(1)
harmonic_sum(7)=1/7+1/6+1/5+1/3+1/2+1

No comments:

Post a Comment