The recursive function F is shown below.
FUNCTION F(a, b)
IF b = 0 THEN
RETURN a
ELSE
RETURN F(b, a MOD b)
ENDIF
ENDFUNCTION(a) State the value returned by the call F(84, 36). [1]
(b) State how many times F is called in total, including the original call, when F(84, 36) is executed. [1]
(c) State what the function F calculates. [1]
(d) Identify the base case in F and explain why a recursive subroutine must have a base case. [2]
- (a) 12(1)
- (b) 3 (calls F(84, 36), F(36, 12), F(12, 0))(1)
- (c) The highest common factor / greatest common divisor of a and b; accept HCF / GCD; NE 'a factor of a and b'(1)
- (d) Base case: when b = 0 (the function returns a without calling itself); accept
IF b = 0 THEN RETURN a(1) - (d) Without a base case the subroutine would keep calling itself and never return / terminate; each call adds a stack frame, so eventually the stack overflows / runs out of memory (and the program crashes); accept: the base case is the stopping condition that allows the calls to unwind and return values(1)
- Answer: (a) 12 (b) 3 (c) The HCF/GCD of a and b (d) Base case is b = 0 (return a); without one the function keeps calling itself, never returns, and stack frames build up until the stack overflows.
- Examiner tip: In (d) say what would actually happen without a base case (endless calls, stack frames building up until stack overflow) rather than just 'it loops forever'.