The new, more efficient exp algorithm is:
int exp(int x, int y) { int i, v = 1; for (i = y; i; i >>= 1) { if (i & 1) { v = v * x; } x = x * x; } return v; }This code is O(|Y|) (in number of word operations). The |Y| notation in computer science denote the size in bits of Y and not the absolute value of Y -- in mathematical terms, this is ceil(log2(Y)) (where ceil(.) denotes the ``ceiling'' function, which rounds up to the nearest integer). The subz version was O(Y), exponentially slower.
Next time, we will go over proofs of correctness of algorithms, how subroutine calls are done (in C/asm) in the MIPS instruction set, what is a stack frame, etc. We'll also briefly go over what compilers do to generate code and the interface between C code and assembly language code. Your homework assignment should not require the use of local variables; the $t registers should be enough.
Homework 3: Write exponentiation subroutine in MIPS, test with spim. See template handout (~/../public/assn3.handout.asm) for the I/O skeleton. You must use the new repeated-squaring exponentiation algorithm. Your turnin must include test cases, and should be well commented.
Before you modify the template code, try it out first: run the command spim -file ~/../public/assn3.handout.asm and click on the run button. Alternatively, you can just run it as spim and click on the load button, whereupon you'll get a pop-up dialog box into which you can type in the filename, and then click on run.
bsy@cse.ucsd.edu, last updated