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.

[Program]
○ integer: factorial(integer: n)
if (n = 0)
return 1
endif
return blank

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(n) returns n × factorial(n - 1). Each call lowers the argument by 1 until it reaches 0, which returns 1. For example, factorial(3) = 3 × factorial(2) = 3 × 2 × factorial(1) = 3 × 2 × 1 × factorial(0) = 6.

Answer (f)

Why not others:

  • •(a) and (e) — call factorial again with an argument that never reaches 0 (n itself, or 1 over and over), so for any n of 1 or more the recursion never ends
  • •(b) — drops the multiplication by n: every chain of calls ends in factorial(0), so it returns 1 for every n
  • •(c) — returns n itself: right for 1 and 2, but 3 for factorial(3) instead of 6
  • •(d) — multiplies only the top two factors: 12 for factorial(4) instead of 24, and 0 for 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.