Factorial

The questions below are due on Sunday November 01, 2026; 11:59:00 PM.
 
You are not logged in.

Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Back to Exercises

Your task is to write the procedure factorial. factorial should take a number n as an argument and return n! as its result. The argument n will be passed through a0, and the result should be placed in a0. Below, we give you a Python implementation for reference. To compute the factorial of n, you should call the mul procedure (using call mul) to do each multiplication, which has been defined for you. The mul procedure takes the multiplier and multiplicand in a0 and a1, and returns the product in a0. You are permitted to use any registers you'd like (as long as you follow the calling convention), except for gp and tp.

def mul(a,b):
    return a * b

def factorial(n):
    running_prod = n
    for i in range(1, n):
        running_prod *= i
    return running_prod

Back to Exercises