Day 10 of My 30-Day Coding Challenge on HackerRank
Day 10 introduced me to the concept of Recursion through a classic problem — calculating the factorial of a number.
Although the challenge expected a recursive solution, I first solved it using an iterative approach with loops, which also helped me understand the factorial logic clearly.
Problem Overview
Today’s challenge focused on:
Understanding factorial calculation
Learning recursion concepts
Using loops to solve repeated multiplication
Building problem-solving logic step by step
We were given an integer n and asked to calculate:
n! = n × (n-1) × (n-2) × ... × 1
Examples:
3! = 6
5! = 120
My Solution
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
What I Did Today
I learned how to:
Use a function to organize code
Apply loops for repeated multiplication
Return values from a function
Understand factorial step by step
Here’s the logic I followed:
1. Create function factorial(n)
2. Set fact = 1
3. Loop from 1 to n
4. Multiply fact by each number
5. Return final result
What I Learned
Today’s key takeaways:
Factorial uses repeated multiplication
Functions make code reusable
Loops can solve factorial easily
There can be multiple ways to solve one problem
Example (n = 5)
fact = 1
1 × 1 = 1
1 × 2 = 2
2 × 3 = 6
6 × 4 = 24
24 × 5 = 120
Final Answer:
120
Important Note
This challenge specifically asked for recursion, so while my loop solution gives the correct factorial value, HackerRank may require a recursive function for full marks.
Recursive version:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
Why This Problem Matters
This problem helps in understanding:
Functions
Loops
Recursion basics
Mathematical logic in coding
Plan for Day 11
- Improve algorithm thinking
💬 Final Thoughts
Day 10 taught me that one problem can have different solutions.
Even though recursion was the goal, solving it with loops first helped me understand the logic better.
Let’s keep learning and growing
