Exponentiation by Repeated Squaring


You may want to try to translate the C code for exponentiation by repeated squaring into MIPS assembler. The C code for this is:
int	exp(int	base,
	    int exponent)
{
	/* pre-condition:  exponent >= 0 */
	int	value;

	if (exponent == 0) {
		value = 1;
	} else {
		value = exp(base * base,exponent/2);
		/* note division by 2 is arithmetic shift right by 1 */
		if (exponent & 1) {
			value *= base;
		}
	}
	return value;
}
This runs in time proportional to the number of bits in the binary representation of the exponent (length in bits is approximately log of the value of the exponent). The naive implementation:
int	exp(int base,
	    int exponent)
{
	int	value = 1;

	while (exponent > 0) {
		value *= base;
		--exponent;
	}
}
runs much slower, in time proportional to the value of the exponent.
[ CSE 80 | ACS home | CSE home | CSE calendar | bsy's home page ]
picture of bsy

bsy@cse.ucsd.edu, last updated Wed Oct 16 22:37:41 PDT 1996.

email bsy