Day 43: Factorial of a Number Solution

Day 43 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Factorial of a Number We were given an integer n. Task was to find n! Factorial means: n! = n × (n-1) × (n-2) … × 1 Example: 5! = 5 × 4 × 3 × 2 × 1 = 120 💻 Iterative Approach 🔹️Initialize result = 1. 🔹️Run a loop from 1 to n. 🔹️Multiply each number with result. 🔹️Return final result. Simple loop. Easy to understand. Time Complexity: O(n) Space Complexity: O(1) 💻 Recursive Approach 🔹️Base case:   ▪️If n == 0 or n == 1 → return 1 🔹️Recursive case:   ▪️Return n × factorial(n-1) Breaks problem into smaller parts. Time Complexity: O(n) Space Complexity: O(n) Due to recursion stack. 📚 What I learned today: ▫️Recursion is based on defining smaller subproblems. ▫️Base case is necessary to stop recursion. ▫️Iterative approach is more space efficient. ▫️Same problem can be solved in multiple ways. Day 43 completed. Strengthening recursion vs iteration concepts 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic

To view or add a comment, sign in

Explore content categories