- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Here's another VBScript version meant to run as an Excel macro.
It assumes the values to be multipled are in cells A2 and B2 of the first Worksheet and it stores all of the intermediate numbers in the cells below as it calculates.
The final output is put in cell C2
Admin
A version for the D programming language; both as an interative function and a template:
Admin
Wow, you make PHP look good, that is pretty impressive.
Admin
In Ruby,
Admin
Ruby, one line, non-recursive:
Admin
Second attempt at C#, this works with negative numbers: public int RussianMultiply(int operand1, int operand2) { int res = 0; while (operand1 != 0) { if (operand1 % 2 == 1) res += operand2; else if (operand1 % 2 == -1) res -= operand2; operand1 /= 2; operand2 *= 2; } return res; }
Admin
Different twist on a Ruby solution:
Admin
I'd argue it's not quite the russian algorithm though, since you've both reversed the operands and you are evaluating a-log2(a) more iterations than would be done in the real algorithm. For example, if I were to feed 5,4 into the russian algorithm, it would make 3 iterations (the left column being 5,2,1). Taking into account that you've swapped the parameters, your algorithm would evaluate 5 iterations (the left column being 5,2,1,0,0), or two more (5 - log2(5)) iterations than you should if you were adhering to the real algorithm, which stops evaluating when reaching 1 in the left column. Your solution also fails for negative values of a.
Admin
second attempt at C# recurisive, this works with negative numbers: public int RecursiveRussianMultiply(int operand1, int operand2) { return operand1 == 0 ? 0 : RecursiveRussianMultiply(operand1 / 2, operand2 * 2) + (operand1 % 2 == 1 ? operand2 : 0) + (operand1 % 2 == -1 ? -operand2 : 0); }
Admin
Admin
Admin
If you want to know how processors multiply, several methods are listed here: wikibooks: multiply Booth's Algorithm some more are listed here, not all easily applicable to microprocessor design: multiplication algorithms
More (basically the peasant's method in hardware!) binary multiplier
Admin
Python:
Ruby:
Admin
All we need is a SAS submission and this thread will be complete.
Admin
Common Lisp
Imperative/iterative and functional solutions. Ain't it nice that Lisp's so versatile? :P
Admin
Yeah, I was saving some characters (at the cost of a lot of memory).
Here's a recursive version that is 48 characters
Admin
Postscript: /rmul{0{2 index 0 eq{exit}if exch dup 1 bitshift 4 1 roll 3 -1 roll dup -1 bitshift 5 1 roll 1 and 1 eq {add}{pop}ifelse}loop exch pop exch pop}def
Admin
All the people who don't know what an optimizing compiler is also fail.
Admin
Common Lisp:
Shorter version of the recursive implementation:
Admin
public String multiply(int a, int b){ return "Murray is awesome"; }
Admin
Damn, you beat me too it. But here you can has lolcode spec 1.2
(Untested)
HAI 1.2 CAN HAS STDIO?
I HAS A X I HAS A Y I HAS A MULTIPL X R NUMBR Y R NUMBR
VISIBLE "CAN HAS X?:)" GIMMEH X VISIBLE "CAN HAS Y?:)" GIMMEH Y
HOW DUZ I RPM YR X AN YR Y I HAS A MUTLIPL ITZ 0 I HAS A MODD I HAS A LOLCAT ITZ MAEK WIN A NUMBR BTW IS DUMMY VARIABLE FOR L00P IM IN YR RPMLOOP UPPIN YR LOLCAT WILE DIFFRINT X AN 1 X R MAEK QUOSHUNT OF X AN 2 A NUMBR Y R PRODUKT OF Y AN 2 MODD R MOD X AN 2 BOTH SAEM MODD AN 1, O RLY? YA RLY, MULTIPL R SUM OF MULTIPL AN Y NO WAI, BTW NOTHING HAPPENS OIC IM OUTTA YR RPMLOOP FOUND YR MULTIPL IF U SAY SO
MULTIPL R RPM X Y
VISIBLE "PRODUKT OF " N X N " N " N Y N " IZ " N MULTIPL N ":)"
KTHXBYE
Admin
C implementation:
int russian(int a, int b) {int c=0,d=a^b;a*=(a<0)?-1:1;for(a<<=1;(a>>=1)!=0;b<<=1)c+=a&0x1?b:0;return((c^d)<0?-c:c);}
Admin
Another python version
Admin
Admin
m(-1,2) .... File "<stdin>", line 1, in <lambda> File "<stdin>", line 1, in <lambda> RuntimeError: maximum recursion depth exceeded
=(
Admin
result: Multiplication of 18 and 23:414 Multiplication of 13 and 13:169
Admin
C# using the delightful LINQ to objects
Admin
Alex thats nice, and very similiar to my ruby/python versions, except where summarization occurs.
I didn't bother with the 3rd acc parameter because ruby/python don't do tail-end optimization on recursive calls any way.
That's probably why many diss recursive solutions, but my profiler tells me theres little difference especially if you compare to solutions using python list comprehensions or ruby's .each iteration.
Admin
NO U!
Admin
#!/usr/bin/env python import sys
try: sys.argv[1] sys.argv[2] except IndexError: numbers = raw_input("Please enter the two integers you wish to multiply separated by a space: ").split(' ') else: numbers = sys.argv[1:3]
left = int(numbers[0].strip()) right = int(numbers[1].strip()) product = 0
while left != 0: if left % 2 != 0: product += right left /= 2 right*= 2
print "The product of " + numbers[0].strip() + " x " + numbers[1].strip() + " is " + str(product)
Admin
Some thoughts...
------------8<------------------- int mult(int a, int b) { int result = 0;
while(a) {
if(a & 0x01) { result += b; }
}
return result; } ------------8<------------------- int mult2(int a, int b) { int result = 0;
if(a != 0) { result = mult2(a >> 1, b << 1);
}
return result; }
Admin
My functional-style java version...
Admin
So you're basically agreeing with the " a * b " solution? Because defining multiplication by using multiplication is kind of weird (ok, I agree is in the spec, but anyway).
And no, when you're using rounding in vb.net (or the "" operator) I can assure you that doesn't get optimized. And C# doesn't get optimized, at least not in IL (but maybe at the JIT level).
Admin
http://www.phy6.org/outreach/edu/roman.htm
This is not a Russian method but an ancient Roman one.
Admin
I admit that this takes a bit of a shortcut: it checks each pair of numbers as it comes up, and adds the second to the result if necessary at that time, rather than saving them all and waiting for the end.
For anyone who really likes whitespace:
Admin
let peasant a b = let rec peasant a b acc = if a = 1 then b + acc else match a%2 with | 0 -> peasant a/2 b2 acc | 1 -> peasant a/2 b2 acc+b in peasant a b 0
Admin
ruby:
Admin
Well, that's freakishly easy.
Admin
Here, for the sake of it, is a Sinclair BASIC version.
Is this the first entry to feature line numbers?
Admin
An F# quicky:
Admin
untested Java, quick and dirty...
public static int mult(int x, int y){
Integer x1 = new Integer(x); int result = 0;
for(int i = 0; i < Integer.toBinaryString(x1).length(); i++){ if(Integer.toBinaryString(x1).endsWith("1")) result += y * (int)Math.pow(2, i); x1 = Integer.rotateRight(x1, 1); } return result; }
Admin
Extrapolated from discussion with Josh Bohde:
m=lambda a,b:b*(a&1)+m(a>>1,b<<1) if abs(a)>1 else a*b
55 chars... not as short but handles all integers.
Admin
Haskell:
Admin
Accounts for either argument being zero, also throws an exception if trying to multiply a negative number. Tested with given main() method
Admin
Admin
So many nice solutions, yet nobody has offered a solution using XSLT yet.
So here is mine. The xsl and xml code can be seen here: http://damastabrain.mine.nu/RPA/highlight.php For a better highlight function (at least Firefox), view the xsl itself: http://damastabrain.mine.nu/RPA/russianPeasantAlgorithm.xsl And ofcourse to show the outcome: http://damastabrain.mine.nu/RPA/russianPeasantAlgorithm.xml
Note: it Does work with negative numbers, on either one of the two or both sides. (Integer only)
Admin
Admin
Forget about the sticker, I played a lot with F# today. Thanks for the motivation.
Admin
Accounts for 0 and negative numbers, tested with main //Earlier posted as guest, now posting as member}
Multiplication of 18 and 23:414 Multiplication of 13 and 12:156 Multiplication of 12 and 12:144 Multiplication of -12 and -12:144 Multiplication of -12 and 12:-144
Admin
Yet another Linq solution: public static int rpm(int a, int b) { return Enumerable. Range(0, a < 2 ? 1 : (int)Math.Ceiling(Math.Log(a % 2 == 0 ? a + 1 : a, 2))) .Select(i => new { L = a / (1 << i), R = b * (1 << i) }) .Where(x => x.L % 2 != 0).Sum(x => x.R); }