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.
bsy@cse.ucsd.edu, last updated