Here is my short implementation of Russian Peasant Multiplication. How can it be improved?
Restrictions : only works when a>0,b>0
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
Here is my short implementation of Russian Peasant Multiplication. How can it be improved?
Restrictions : only works when a>0,b>0
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
I think it's incomplete, and very hard to read. What specific sort of feedback were you looking for?
I think it's a pretty poor attempt bragging about code which, although being supposedly smart, it's obfuscated to the point that no sane developer would ever use it on production code.
...Once again, what was your question?
p
is not initialised.
What happens if a
is zero?
What happens if a
is negative?
Update: I see that you have updated the question to address the above problems. While your code now appears to work as stated (except for the overflow problem), it's still less readable than it should be.
I think it's terrible This is exactly the same code from the compiler's point of view, and (hopefully) a lot clearer
int sum = 0;
while(1)
{
sum += (a & 1) * b;
if(a == 1)
break;
a = a / 2;
b = b * 2;
}
And now I've written it out, I understand it.
There is still a multiplication in the loop. If you wanted to reduce the cost of the multiplications, you could use this instead:
for(p=0;p+=(-(a&1))&b,a!=1;a>>=1,b<<=1);
This is for a code obfuscation contest? I think you can do better. Use misleading variable names instead of meaningless ones, for starters.
It's a stunning example of unparalleled genius, I am in awe of your 1337 hacker skills.
int RussianPeasant(int a, int b)
{
// sum = a * b
int sum = 0;
while (a != 0)
{
if ((a & 1) != 0)
sum += b;
b <<= 1;
a >>= 1;
}
return sum;
}
There is an really easy way to improve this:
p = a * b;
It has even the advantage that a or b could be less than 0.
If you look how it really works, you will see, that it is just the normal manual multiplication performed binary. You computer does it internaly this way (1), so the easiest way to use the russian peasant method is to use the builtin multiplication.
(1) Maybe it has a more sophasticated algorithm, but in principle you can say, it works with this algorithm
So many downvotes. I don't see any harm he caused by posting this!
P.S. For "learning"[playing around], it's ok to code like that. But professionally I'd not expect you to code like this!
Answer with no multiplication or division:
function RPM(int a, int b){
int rtn;
for(rtn=0;rtn+=(a&1)*b,a!=1;a>>=1,b<<=1);
return rtn;
}