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);
It can be improved by adding whitespace, proper indentation, and a proper function body:
See? Now it's clear how the three parts of the
for
declaration are used. Remember, programs are written mainly for human eyes. Unreadable code is always bad code.And now, for my personal amusement, a tail recursive version:
This is for a code obfuscation contest? I think you can do better. Use misleading variable names instead of meaningless ones, for starters.
Answer with no multiplication or division:
I think it's terrible This is exactly the same code from the compiler's point of view, and (hopefully) a lot clearer
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:
I don't find it particularly terrible, obfuscated or unreadable, as others put it, and I don't understand all those downvotes. This said, here is how I would "improve" it: