if b is even, a*b is (a*2)*(b/2). If b is odd, a*b is ((a*2)*(b/2) + a) where b/2 is an integer divide, e.g. the result is rounded down. If we apply this fact recursivly, we have the following method:
To put a number a times a number b into a number c: Set a number c to zero. While b is more than zero if b is odd, add a to c. Double a. Halve b.
In C, this might be:
unsigned int mult_rp(unsigned int a, unsigned int b){ int c = 0; // initialize result while (b > 0) { if (b & 1) //odd? c += a; //accumulate a <<= 1; //shift left 1 bit, doubling b >>= 1; //shift right 1 bit, halving } return c; }
This is also useful for raising a number to an exponent with the minimum number of multiplications, but instead of starting with 0, we start with 1, and instead of adding and doubling, we multiply and square.
int exp_rp(int a, int b) { c = 1; //initialize to 1 instead of 0 while (b > 0) { if (b & 1) //odd? c *= a; //multiply the result by a b >>= 1; //shift right 1 bit, halving a *= a; //square } return c; }
See also: