5.48 · exercise
Call yourself
Write fact, a subroutine that computes a factorial by calling itself. main reads n, calls fact, and prints n! = and the answer.
Each call to fact needs its own frame (lr must survive the recursive bl), and n has to outlive the recursive call, which means a callee-saved register that you save on entry and restore on exit. main itself keeps n in x19 across the call, so a fact that forgets to restore it prints the wrong n. Base case first: when n is 1 or less, the answer is 1. Otherwise it is n * fact(n - 1).
What is checked
10! = 3628800printed on its own line for the10in the stdin box- the program exits cleanly
- a real call chain does it:
factbuilds a frame (stp) and calls itself (bl factinsidefact), with no precomputed answer - the same holds for other values of
nyou do not see, from 0 up to 20
specification
stdin10
stdoutprints the right output
exitexits with the right code
sourceuses
bl fact in factsourceuses
stp in factsourcedoes not hardcode the answer
hiddenright output and exit code on 4 more inputs you do not see
We run your program on the input above and on the hidden ones, and compare what it does. Nothing is matched against a stored solution.