Using shifts
/*peasant.c - an implementation of the Russian Peasant
multiplication algorithm, which implements binary
multiplication as a series of shifts and additions.
Copyright (c) 1998 Matthew Belmonte.*/
int main()
{
/*declarations*/
int left_multiplicand, right_multiplicand; /*inputs*/
register int mL, mR; /*multiplicand registers*/
register int acc; /*product accumulator*/
/*inputs*/
left_multiplicand = 6;
right_multiplicand = 9;
/*the Russian Peasant algorithm (short form!)*/
/*invariant: mL*mR+acc==left_multiplicand*right_multiplicand*/
for(mL=left_multiplicand, mR=right_multiplicand, acc=0;
mL != 0;
mL&1? mL&=~1, acc+=mR: (mL>>=1, mR<<=1))
;
printf("%d * %d = %d\n", left_multiplicand, right_multiplicand, acc);
return 0;
}
Next slide