IPA FE Subject B sample Question 7
A question IPA Japan published in 基本情報技術者試験 科目B サンプル問題 問7, translated into English. ITPEC is based on the same exams.
From the answer group below, select the correct answer to be inserted into blank in the program.
The function factorial receives a non-negative integer n as an argument, and returns its factorial. The factorial of a non-negative integer n is 1 when n is 0; otherwise, it is the number obtained by multiplying together all the integers from 1 to n.
Answer group
Explanation
n × factorial(n - 1) — the recursive case multiplies n by the factorial of the number one smaller, and the case n = 0 stops the recursion.
For n ≥ 1, n! = n × (n − 1) × … × 1 = n × (n − 1)!, so factorial( returns n × factorial(. Each call lowers the argument by 1 until it reaches 0, which returns 1. For example, factorial( = 3 × factorial( = 3 × 2 × factorial( = 3 × 2 × 1 × factorial( = 6.
Answer (f)
Why not others:
- •(a) and (e) — call
factorialagain with an argument that never reaches 0 (nitself, or 1 over and over), so for anynof 1 or more the recursion never ends - •(b) — drops the multiplication by
n: every chain of calls ends infactorial(, so it returns 1 for every0) n - •(c) — returns
nitself: right for 1 and 2, but 3 forfactorial(instead of 63) - •(d) — multiplies only the top two factors: 12 for
factorial(instead of 24, and 0 for4) factorial(1)
Key rule: A recursive function needs a base case and a recursive call on a smaller argument that leads to it; here n! = n × (n − 1)! with 0! = 1.
Math & Numbers · AI-written, may contain errors
This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.