w3resource

Python Data Structures and Algorithms - Recursion: Calculate the harmonic sum


8. Harmonic Series Sum Using Recursion

Write a Python program to calculate the sum of harmonic series upto n terms.

Note: The harmonic sum is the sum of reciprocals of the positive integers.

Example:

harmonic series

Sample Solution:-

Python Code:

# Define a function named harmonic_sum that calculates the harmonic sum up to 'n' terms
def harmonic_sum(n):
    # Check if 'n' is less than 2 (base case for the harmonic sum)
    if n < 2:
        # If 'n' is less than 2, return 1 (base case value for the harmonic sum)
        return 1
    else:
        # If 'n' is greater than or equal to 2, calculate the reciprocal of 'n'
        # and add it to the result of recursively calling the harmonic_sum function with 'n - 1'
        return 1 / n + harmonic_sum(n - 1)

# Print the result of calling the harmonic_sum function with the input value 7
print(harmonic_sum(7))

# Print the result of calling the harmonic_sum function with the input value 4
print(harmonic_sum(4))

Sample Output:

2.5928571428571425                                                                                            
2.083333333333333 

Flowchart:

Flowchart: Recursion: Calculate the harmonic sum.

For more Practice: Solve these Related Problems:

  • Write a Python program to recursively calculate the sum of the harmonic series up to n terms.
  • Write a Python program to implement a recursive function that computes 1 + 1/2 + 1/3 + ... + 1/n.
  • Write a Python program to use recursion to sum the reciprocals of the first n positive integers.
  • Write a Python program to calculate the harmonic sum recursively and compare the result with an iterative loop version.

Go to:


Previous: Write a Python program to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).
Next: Write a Python program to calculate the geometric sum of n-1.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.