please dont rip this site

Russian Peasent Math: Multiplication and Exponentiation

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;
	}

Exponentiation

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 09:05, local time: 2024/12/22 16:03,
TOP NEW HELP FIND: 
3.138.134.163:LOG IN

 ©2024 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?
Please DO link to this page! Digg it! / MAKE!

<A HREF="http://sxlist.com/techref/method/math/russianpeasent.htm"> Russian Peasent Multiplication and Exponentiation</A>

After you find an appropriate page, you are invited to your to this massmind site! (posts will be visible only to you before review) Just type a nice message (short messages are blocked as spam) in the box and press the Post button. (HTML welcomed, but not the <A tag: Instead, use the link box to link to another page. A tutorial is available Members can login to post directly, become page editors, and be credited for their posts.


Link? Put it here: 
if you want a response, please enter your email address: 
Attn spammers: All posts are reviewed before being made visible to anyone other than the poster.
Did you find what you needed?

 

Welcome to sxlist.com!


Site supported by
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 sxlist.com!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  .