Recursion that steps by two — Pseudocode Aptitude Question
Recursion that steps by two: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What is printed?
Function F(Integer n)
If n <= 1 Then
Return 1
End If
Return n * F(n - 2)
End Function
Print F(7)Options
- 35
- 105
- 210
- 5040
Show the answer and the worked solution
Correct answer: B. 105
Worked solution
- F(7) = 7 F(5), F(5) = 5 F(3), F(3) = 3 * F(1), and F(1) = 1.
- Substituting back gives 7 5 3 * 1.
- That product is 105.
Answer: 105.
The idea
This is the double factorial: it multiplies every second integer down to the base case. The distractor 5040 is 7 factorial, which you get by wrongly stepping down by 1.
Shortcut. Only odd numbers are ever multiplied, so the answer must be odd, which rules out 210 and 5040; 7 × 5 × 3 = 105.
Common trap. 5040 is 7!, the result of stepping n down by 1 instead of 2 so that the even factors 6, 4 and 2 slip into the product.