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:
file: /Techref/method/math/russianpeasent.htm, 2KB, , updated: 2021/6/13 10:05, local time: 2022/5/23 07:53,

©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://www.sxlist.com/Techref/method/math/russianpeasent.htm"> Russian Peasent Multiplication and Exponentiation</A> 
Did you find what you needed? 
Welcome to sxlist.com!sales, advertizing, & kind contributors just like you! Please don't rip/copy (here's why Copies of the site on CD are available at minimal cost. 
Welcome to www.sxlist.com! 
.