- 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
I've never seen a comments page fill up so quickly (at least, not with legitimate and well thought out comments). This has been a rousing success!
Admin
This is PHP, although it probably works as Perl too.
Admin
This one ist Tcl/Tk http://www.tcl.tk
proc russ {a b} { set erg 0 if {$a < 0} { set a [expr {-1 * $a}] set b [expr {-1 * $b}] } for {} {$a} {} { if {$a&1} { incr erg $b puts [format %5d%5d%5d $a $b $erg] } else { puts [format %5d%5d $a $b ] } set a [expr {$a >> 1}] set b [expr {$b << 1}] } puts "==========[format %5d $erg] =======" return $erg } russ 18 23
Admin
Here's the 'schoolbook' perl version to demonstrate recusive fuctions. No fancy operators, indentation where appropriate and variable names which provide no description of that they do. And of course no comments.
It's kind of beautiful.
print axb($ARGV[0],$ARGV[1]) . "\n"; sub axb { my $a = shift; my $b = shift; my $total = 0; if ($a == 1) { return $b; } else { if ($a % 2) { $total += $b; } $ah = int($a / 2); $bh = $b * 2; return $total + axb($ah,$bh); } }
Admin
People still using * directly.
That's cheating yourself!
Try harder!
Admin
Admin
You beat me to the punch, but there is some unnecessary code in there (you don't need to clear the carry before a LSR). And trashing X is unnecessary since you can test for zero just as fast with LDA $02. Or with some crazy jujitsu to save a byte... Here's my version, handles 8-bit operands:
Admin
Admin
Spreadsheet...
First number goes in A2 A3 through A41 have "=TRUNC(A2/2)", "=TRUNC(A3/2)", etc (enter in A3, drag lower-right corner to expand to full range, in Excel at least the formulas in the additional cells will be adjusted to keep the relative positions of the referenced cells the same).
Second number goes in B2 B3 through B41 have "B22", "B32", etc.
C2 through C41 have "=IF(MOD(A2, 2) = 1, B2, 0)", "=IF(MOD(A3, 2) = 1, B3, 0)", etc.
D2 has "=SUM(C2:C41)", and is the result.
A1 through D1 have headers "First Number", "Second Number", "Cross out where A is even", and "Result".
This function can be called by using the MSOffice interop libraries to open the spreadsheet, populate A2 and B2, and read D2 (there might be another step in between to tell it to run the actual calculation, I forget).
Admin
Just my own little recursive Java solution:
Admin
MSIL:
.method private hidebysig static int64 Multiply(int64 f, int64 s) cil managed { .maxstack 3 start: ldarg.0 dup ldc.i4.0 beq.s done ldc.i4.1 and ldarg.1 mul next: ldarg.0 ldc.i4.1 shr ldarg.1 ldc.i4.1 shl call int64 RussianMult.Program::Multiply(int64, int64) add done: ret }
Admin
As we haven't had any m68k yet:
20 bytes in binary :)
Admin
After looking at some of the other solutions I realize that I don't do this kind of programming and why. This kind of boolific bitshifty goodness is brain melting. But it was fun. But boy am I shamed by the cleverness of many of the other solutions.
Admin
This revision of The Wolf's PHP solution handles negative numbers and displays the columns in a table with unused rows crossed out.
Admin
Common Lisp:
No multiplication.
The parens might be unbalanced since I'm writing this from my phone.
Admin
33 characters in C#:
(a,b)=>a==1?b:m(a/2,b2)+b(a&1);
Implementing this lambda expression in code is left as an exercise for the reader (hint: assign it to a delegate named 'm')
Admin
Reading many of these ingenious, esoteric, or even simple and straight-forward implementations in various languages makes me very happy that I don't often have to use languages other than PHP.
Admin
A slightly more sophisticated python version:
why is code double-spaced or is that my firefox?
Admin
Just because I think using * isn't in the spirit of this.
n will handle negatives. 118 characters, including newline.
Admin
One last tweak: forgot to switch the floor($x / 2) for a bit shift.
Admin
Admin
Obligatory solution from a Haskell neophyte:
Admin
Did this in Python, and it made me remember why I like it so much.
Admin
long rmultiply(long a, long b) { return (a==1)?b:((a&1)?b:0)+rmultiply(a>>1,b<<1); }
Admin
mIRC
Admin
I like it since it does the builtin multiply anyway, and then the calculation. NB: infinite loops may happen with -ve numbers.
Admin
My implementation is in C (or C++).
If you accuse me of initially using std::list and std::pair I'll deny it! Deny!
Admin
Including Perl? :-)
Admin
Quick Solution in Delphi. Accompanying form has a StdCtrls Memo to display columns named Memo1. Two edit boxes allow input of multiplicands (edit1 := Leftside, edit2 := Rightside). ClearValues simply clears the edit boxes and resets all totals. lblResult is a label displaying the result. This routine will not handle negative numbers.
procedure TForm1.ComputeRpProduct; var vTotal : Integer;
{SUB} procedure AddLineToMemo; begin if (Leftside mod 2) <> 0 then begin Memo1.Lines.Add(inttostr(Leftside) + ' ' + inttostr(RightSide)); vTotal := vTotal + Rightside; end else begin Memo1.Lines.Add(inttostr(Leftside) + ' ' + inttostr(RightSide) + ' ---'); end; end; {/SUB}
begin if (Leftside <> 0) and (Rightside <> 0) then begin
end else begin ShowMessage('Please enter numeric nonzero values to compute.'); ClearValues; Edit1.setfocus; end;
end;
Admin
I didn't read all the comments but this is also called "Shift and Add" in information processing, and this is typically how computers actually implement multiply. Thus, I propose this "hardware accelerated" version of the algorithm:
return a*b;
(see http://en.wikipedia.org/wiki/Multiplication_algorithm#shift_and_add for more info)
Admin
I missed a lot previously...enough to make me register so I can erase evidence of future blunders. This PHP handles negative numbers, outputs an HTML table with the unused rows crossed out, and is derived from the code posted by The Wolf on page one of the comments:
Admin
int russian_peasant(int n1, int n2) { int product = 0, sign = 1;
}
Admin
Recursive Common Table Expression in MS SQL Server:
WITH russian AS ( SELECT 45 a, 76 b UNION ALL SELECT a / 2, b + b FROM russian WHERE a > 1) SELECT ISNULL(SUM(b), 0) AS product FROM russian WHERE a & 1 = 1
Admin
C++ using for loop
for(int a=3,b=5,c=0;a>0;c+=(a&1?b:0),a>>=1,b<<=1,std::cout<<c<<std::endl);
Admin
Admin
Supporting negative numbers: long multiply(long a, long b) { return (a<0)?-multiply(-a,b):(a==1)?b:((a&1)?b:0)+multiply(a>>1,b<<1); }
Admin
In JavaScript var s = 7 * 38;
The binary approach is taken behind the scenes.
Admin
Admin
common lisp from Emacs:
(defun mymult (nn mm) (loop for n = nn then (/ n 2) for m = mm then (* m 2) until (< n 1) sum (if (oddp n) m 0)))
Admin
Solution in PHP :
function peasant($a,$b) { $s = 0; while($a > 1) { $b *= 2; $a = floor($a/2); if(($a % 2) != 0) { $s += $b; } }
}
Could probably be made more efficient by using bitwise operations instead of base mathematical operators. Well, would obviously be more efficient NOT being written in PHP, too.
Admin
My recursive PHP CLI version. (Inputs must be >0) The output will create the table as shown in the instructions and even cross out the even rows.
Admin
Non-recursive MSIL, more stack-based:
.method private hidebysig static int64 m(int64 f, int64 s) cil managed { .maxstack 4 ldc.i4.0 conv.i8 start: ldarg.0 ldc.i4.0 beq.s done ldarg.0 ldc.i4.1 and ldarg.1 mul add ldarg.0 ldc.i4.1 shr starg.s 0 ldarg.1 ldc.i4.1 shl starg.s 1 br.s start done: ret }
Admin
This was perfectly timed, since I'm learning Haskell. It gave me the perfect opportunity to try out what I've learned so far :). So to add to the already numerous Haskell solutions, here's mine (I noticed it looked similar to others, so I guess I'm getting the hang of this functional programming thing :D):
I'm sure there's more concise ways to do this, but this works :).
Admin
Unobfuscated Perl:
Admin
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var leftNum = 0; var rightNum = 0;
}
Admin
You didn't add the first row in your first example.
Admin
non recusive version in c# with 64bit in because russians love big numbers right?
Admin
Admin
Addendum (2009-07-22 13:34): I suppose you could replace...
...with...
:P
Addendum (2009-07-22 13:36): No, no, wait, no you couldn't... Infinite recursion...
Admin
Scheme:
Assumes fold:
Easily done without the list, I thought it was more in keeping, though.