Factorial (Recursive and Iterative)
Write two functions, factorialrecursive(n) and factorialiterative(n), both returning n!, and print both results for the same input to confirm they agree.
What the problem means: n! (n factorial) is the product of every whole number from 1 to n. There are two classic ways to compute it — recursion (a function calling itself) and iteration (a loop) — and this problem asks you to write both.
Approach: factorialrecursive multiplies n by factorialrecursive(n - 1), stopping at the base case n == 0 or n == 1. factorial_iterative just multiplies a running total in a loop from 2 to n.
Input: One line: a whole number n.
Output: Two lines: Recursive: <n!> Iterative: <n!>
5
Recursive: 120 Iterative: 120
- 0 <= n <= 20
Hint 1
Base case for the recursive version: 0! and 1! are both 1.
Hint 2
Recursive case: n! = n * (n - 1)!.
Hint 3
For the iterative version, start result at 1 and multiply it by every number from 2 to n in a loop.
factorialrecursive multiplies n by the factorial of n - 1, all the way down to the base case (0 or 1, both defined as 1). factorialiterative reaches the same answer without any function calling itself: start a running total at 1 and multiply it by every integer from 2 up to n in a simple loop. Both approaches must produce identical results for the same n.