- 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
in C# public int RussianMultiply(int operand1, int operand2) { int res = 0; while (operand1 > 0) { if (operand1 % 2 == 1) res += operand2; operand1 /= 2; operand2 *= 2; } return res; }
Admin
Yet another Scheme solution
;;proper R5RS (define (rusmult a b) (cond ;;special cases ((= a 0) 0);; okay, it's dirty, but i'm way to lasy ((= b 0) 0);; to try to come up with something better ((negative? a) (* -1 (rusmult (* -1 a) b))) (else (if (= a 1) ;; real computation (+ (if (odd? a) b 0)) (+ (if (odd? a) b 0) (rusmult (if (even? a) (/ a 2) (/ (- a 1) 2)) (* b 2)))))))
Admin
Recursive in C# public int RecursiveRussianMultiply(int operand1, int operand2) { return operand1 == 0 ? 0 : RecursiveRussianMultiply(operand1 / 2, operand2 * 2) + (operand1 % 2 == 1 ? operand2 : 0); }
Admin
C# solution (boilerplate not included)
Admin
Scheme
(define (mult a b) (cond ((= b 1) a) ((= (remainder b 2) 1) (+ b (mult (* 2 a) (quotient b 2)))) (else (mult (* 2 a) (/ b 2)))))
not tested CAPTHA: vereor
Admin
Recursive C# in one line :)
private static long m(long f, long s) { return ((f&1)==1?s:0)+(f>0?m(f>>1,s<<1):0); }
Ok, it's just like the perl sample. Here, how it should be read:
private static long m(long f, long s) { return ((f&1)==1?s:0)+(f>0?m(f>>1,s<<1):0);
}
And for the whole "I can do it in a few chars" thing, from the return to the colon it's only 43 characters.
Admin
An ABAP solution that compiles:
Admin
ugh, i meant it that way
Admin
This is going to get lost in the mix, but here's my take.
Note: I'm betting that most of the naive implementations people have done don't function correctly when multiplying negative numbers. This one does.
Admin
Admin
Some considerations for speed optimisation:
Admin
Here's mine, in Python. It works for all integers.
Admin
Mine on javascript function peasentDevide(a, b){r=0;while(a!=0){if (a%2==1)r+=b;a=Math.floor(a/2);b=b*2;}return r;}
Admin
Wrote in D language :P but the mult function should work also in C++, I think...well, with unsigned int instead of uint :P:
import std.stdio; import std.string;
int mult(uint fst, uint snd) { uint result;
}
void main(string[] args) { if(args.length != 3) { writefln("Usage: %s <num> <num>", args[0]); return 0; } if(!args[1].isNumeric()) { writefln("First argument isn't a number"); return 0; } if(!args[2].isNumeric()) { writefln("Second argument isn't a number"); return 0; }
}
To run put it in a file and use the gdc compiler....
Admin
In Python (Works with 0 and negative numbers!)
def p_mult(num1, num2) : if num1 == 0 or num2 == 0 : return 0 sign = bool(num1 < 0) ^ bool(num2 < 0) num1 = abs(num1) num2 = abs(num2) dat = [[num1, num2]] while num1 != 1 : num1 /= 2 num2 *= 2 dat.append([num1, num2]) total = 0 for n in dat : if n[0] % 2 == 1 : total += n[1] if sign : return total * -1 else : return total
http://www.codeskilled.com
Admin
Common Lisp:
C:
Admin
My solution in LUA:
Admin
Admin
Windows XP batch file:
Admin
Forgive, i missed the automagic vivification of c to existance and 0
Admin
Python 2.6
51 characters
Admin
Since everyone is bragging about shifting instead of multiply/divide, here is a Pascal version with shifting:
You could strip the
part, but it would be slower I guess.
Admin
Shorter: return f>0?m(f>>1,s<<1)+(f&1)*s:0;
Just realized that ( (a&1) == 1? s : 0 ) === ( (a&1)*s )
34 chars without the function header.
Admin
And, for even more fun, with a custom operator
Admin
Python:
Admin
Final version of my ruby function, slightly altered with some cribbage from halber_mensch to handle all integers.
Admin
Last one I submit, I promise! :)
Admin
Or
X gets a list of powers of two starting with 1
Y gets a list of B times powers of two
Z gets a list of (A/power of two) mod 2 (0 or 1)
RET gets the sum of the list of Y and Z elements multiplied together.
4 lines, no loops, no recursion, and only one Greek letter!
NOT TESTED. Written using a memory of APL not exercised in 25 years.
Admin
Well that one wins Best Abuse Of The Rules.:) I've only seen one C preprocessor nasty so far.... any more takers?
Admin
Here is my MS-Windows Batch file:
Now, how does one get code to single-space?
Admin
A database query syntax error has occurred. This may indicate a bug in the software. The last attempted database query was:
from within function "MediaWikiBagOStuff::_doquery". MySQL returned error "1194: Table 'mw_objectcache' is marked as crashed and should be repaired (localhost)".
Admin
The problem says two numbers, not two integers, so here's the first draft of a PHP solution that will handle decimal fractions (and also negative numbers):
Test code:Admin
I know everybody wants it :)
Hopefully none of it was removed.
Also, everything after the first . is disabled debugging code. Remove the [-] to see what is left of the memory.
Admin
48 characters in javascript:
function m(a,b){return a>1?a%2b+m(a>>1,b2):b;}
Admin
Didn't test it, but I think this will infinite loop if the first number is 0;
Admin
Admin
Efficient C solution:
int russianMult( int a, int b ){
}
Admin
All of these solutions are soooooo slooooooooow. Try this one out. Just call the function you need! Ex: for 5 x 18, call "F5x18();". Note: Doesn't yet work for all values, but I'm working on it.
Admin
While I haven't checked if it already exists, here a non-recursive Ruby solution overwriting the default operator.
I couldn't test it, so it'll probably not work.
But it has comments, works with negative numbers, and doesn't interfere with non-integral multiplication.
Addendum (2009-07-22 11:36): Okay, so this is one of the least clever solutions... but it is commented like no other. Does this get me a sticker?
Addendum (2009-07-22 13:32): Damn! I'm stupid. Of course, sgn*result is incorrect. Take this instead:
(gotta close those tags.)Admin
Admin
Exercise for the reader, as always.
Or if you insist:
Admin
Or how about this:
Using multiply and divide expands our domain from N × N to Z × Z. If that's not worth the minor performance penalty, you're doing much more interesting work than I am.Admin
Since I read this as "Multiply exactly like russian peasants would" then I did it the old-fashioned C# way.
Admin
Dammit...Someone beat me the the CF solution...
Where are the COBOL developers? Don't make me bust out my college COBOL!!!
Admin
Zor, this is very useful. Perhaps something like this would make it easier for the user?
#define multiply(X, Y) F##X##x##Y ()
Admin
Did that already...
But...
sub t{$[0]?t($[0]>>1,$[1]<<1)+($[0]&1)*$_[1]:0}
52 char is about as far down as I can get it, and does not handle (-) due to Perl using C shifts, which dont operate properly on (-)..
Admin
inline bool shift(unsigned int& result, unsigned int a, unsigned int b) { return result += a & 1 ? b : 0; }
unsigned int RM(unsigned int a, unsigned int b) { unsigned int result = 0; while (a != 1 && shift(result, a>>=1, b<<=1)) { } return result; }
Admin
public class NotCheating {
}
Admin
Well, what's a promis if you don't break it? :)
Admin
C++ version