Basic problems in recursion.

Basic problems in recursion.

ยท

2 min read

Title: "My Journey into Recursion: Day 5 of #100DaysOfCode Challenge"

Recursion: Unveiling the Elegance of Divide and Conquer

On the fifth day of my #100DaysOfCode challenge, I learnt about basic problems in recursion.

Here are 10 fundamental problems I explored, each unlocked with the magic of recursion:

  1. Factorial: Problem: Calculate the factorial of a non-negative integer. Explanation: The factorial of an integer n is the product of all positive integers from 1 to n. Code:

     def factorial(n):
         if n == 0:
             return 1
         else:
             return n * factorial(n - 1)
    
  2. Fibonacci Sequence: Problem: Generate the nth Fibonacci number. Explanation: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. Code:

     def fibonacci(n):
         if n <= 1:
             return n
         else:
             return fibonacci(n - 1) + fibonacci(n - 2)
    
  3. Sum of Digits: Problem: Find the sum of the digits of a positive integer. Explanation: Recursively sum the digits of the integer. Code:

     def sum_of_digits(n):
         if n < 10:
             return n
         else:
             return n % 10 + sum_of_digits(n // 10)
    
  4. Exponentiation: Problem: Calculate the result of x raised to the power of y. Explanation: Use recursion to repeatedly multiply x by itself y times. Code:

     def power(x, y):
         if y == 0:
             return 1
         else:
             return x * power(x, y - 1)
    

They are certainly amazing to learn the basics of recursion and get a hang of it.

Did you find this article valuable?

Support Ashish Guleria by becoming a sponsor. Any amount is appreciated!

ย