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:

- http://mathforum.org/dr.math/faq/faq.peasant.html Imagine multiplying 9 * 8 as counting the squares in a set of blocks stacked 8 high and 9 wide. Now re-arrange them half as high, e.g. 4 high; they will be 18 columns wide. And again; 2 high, 6 wide, and finally, 1 block high: There are 72 blocks in a line. Now think of multiplying 8 * 9 or a set of blocks 9 high and 8 wide. Because we can't restack them exactly half as high, we take off the top row of 8 and set them aside, then we continue with 4 high, 16 wide, 2 high, 32 wide, 1 high 64 wide... plus the 8 we put aside is 72. Notice we "put blocks aside" when the stack was an odd number of blocks high; when it was 9 high, and in both cases, when they were 1 high.

file: /Techref/method/math/russianpeasent.htm, 2KB, , updated: 2021/6/13 09:05, local time: 2022/12/6 04:58, |

©2022 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions?<A HREF="http://massmind.org/Techref/method/math/russianpeasent.htm"> Russian Peasent Multiplication and Exponentiation</A> |

Did you find what you needed? |

## Welcome to massmind.org! |

## Welcome to massmind.org! |

.