1713984680

Problem-solving exercises that you can solve using recursion in Java or Python


For me, one of the ways to better understand programming concepts and solve certain coding-related problems is to always practice and always take on some challenges, even if we often already know what the solution is. So here again are 10 problem-solving exercises that you can solve using recursion in Java or Python: 1. **Factorial Calculation**: Write a recursive function to calculate the factorial of a given number. 2. **Fibonacci Sequence**: Implement a function to generate the nth Fibonacci number recursively. 3. **Binary Search**: Write a recursive function to perform a binary search on a sorted array. 4. **Power Function**: Implement a recursive function to calculate the power of a number, i.e., x^n. 5. **Greatest Common Divisor (GCD)**: Write a recursive function to find the GCD of two numbers using Euclid's algorithm. 6. **Tower of Hanoi**: Solve the Tower of Hanoi problem using recursion. 7. **Merge Sort**: Implement the merge sort algorithm using recursion. 8. **Palindrome Check**: Write a recursive function to check if a given string is a palindrome. 9. **Subset Sum**: Write a recursive function to find if there exists a subset of a given array whose sum equals a given target sum. 10. **Permutations and Combinations**: Write recursive functions to generate permutations and combinations of a given set of elements. These exercises vary in difficulty and complexity, so you can start with simpler ones and gradually move to more challenging ones as you gain proficiency in recursion. As a solution to the factorial calculation we have: ```java public class Factorial { public static int factorial(int n) { if (n == 0 || n == 1) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { int number = 5; // Example number int result = factorial(number); System.out.println("Factorial of " + number + " is: " + result); } } ``` For Fibonacci Sequence: ```java public class Fibonacci { public static int fibonacci(int n) { if (n <= 1) { return n; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } public static void main(String[] args) { int n = 10; // Example Fibonacci sequence index System.out.println("Fibonacci sequence at index " + n + " is: " + fibonacci(n)); } } ``` feel free to leave your doubts or even solve any of them in the comments. Thank you

To comment this publication you need to be logged in.