ITPEC FE Subject B October 2024 Question 4

From the answer group below, select the correct combination of answers to be inserted into A and B in the program.

The procedure primeFactors outputs the prime factors for the input values as its argument. The first few prime numbers are 2, 3, 5, 7, 11, and 13. For instance, if the input integer is 12, the output is “2×2×3”. If the input integer is 78, the output is “2×3×13”. The input integer must be greater than 1.

[Program]
○ primeFactors(integer: num)
integer: i
i ← 2
do
if (A)
num ← integer part of (num ÷ i)
output i
if (B)
output "×"
endif
else
i ← i + 1
endif
while (B)

Answer group

OptionAB

Explanation

A: num mod i = 0, B: num > 1 — divide out i while it divides num, move to the next i when it does not, and stop once num is down to 1.

Trace for 12:

inumnum mod iactionoutput so far
2120num becomes 6; 6 > 12×
260num becomes 3; 3 > 12×2×
231i becomes 32×2×
330num becomes 1; 1 > 1 is false2×2×3

The while test 1 > 1 is false, so the loop ends with 2×2×3. Blank B serves twice, because both questions are the same: is anything left to factor? If so, another factor follows (print ×) and the loop continues. Each i that divides num is prime, because all smaller factors have already been divided out.

Answer (c)

Why not others:

  • •(a) — num < 1 is never true for a positive num, so nothing is divided out; i becomes 3, the while test 12 mod 3 ≠ 0 is false, and the output is empty
  • •(b) — num > 1 divides without checking divisibility: 12 becomes 6 and 3 while 2 is output twice, then 3 mod 2 = 0 is false and the loop stops at "2×2", losing the factor 3
  • •(d) — the divisibility test is inverted: 12 is divisible by 2, so i moves on to 3, and the while test num < 1 is false at once, so nothing is output

Key rule: In trial division keep dividing by the same i while num mod i = 0 before moving on, and loop while the remaining quotient is greater than 1.

Math & Numbers · AI-written, may contain errors

This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.