- 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
You've just forget to sum the first line...
Admin
I will blame this on poor specifications.
Admin
Admin
SQL function using columns
CREATE FUNCTION RussianMultiply (@Num1 int, @Num2 int) RETURNS int AS BEGIN
CREATE TABLE #Columns(C1 int, C2 int)
WHILE @Num1 >= 1 BEGIN
END
DELETE FROM #Columns WHERE C1 % 2 = 0
RETURN SUM(C2) FROM #Columns
END
Admin
Haskell, point-free style:
russian = curry $ sum . map snd . filter (odd.fst) . takeWhile ((>0).fst) . iterate ((
div
2) *** (*2))Admin
Nice idea. F# solution, without much thoughts put into it (in other words: Nicer solutions probably exist) and assuming #light:
Admin
I think we did one worse.
Admin
All the people looping on 1 instead of 0 fail. All the people using multiplication and division instead of shifting (except in languages where there is no shifting) also fail.
Admin
ColdFusion:
<cffunction name="multiply" returntype="numeric"> <cfargument name="x" required="Yes" type="numeric"> <cfargument name="y" required="Yes" type="numeric"> <cfargument name="total" required="no" type="numeric">
</cffunction>
Glad I use Java these days.
Admin
Another C# one: private int Multiply(int a, int b) { int result = 0, aBy2, bBy2;
Admin
For those "handling negatives and zero" - the correct behaviour for these, given the literal description of the algorithm, is to loop forever, because the left hand column will never equal 1. (Not that my previous solution gets this right either)
Admin
2nd attempt:
<cffunction name="multiply" returntype="numeric"> <cfargument name="x" required="Yes" type="numeric"> <cfargument name="y" required="Yes" type="numeric"> <cfargument name="total" required="no" type="numeric"> </cffunction>Admin
Clue:
3420 - 3344 = 76
Admin
Javascript version:
Admin
public static int Multiply( int op1, int op2 ) { return Mult( Math.Abs(op1), op2*op1/Math.Abs(op1) ); }
private static int Mult( int op1, int op2 ) { if( op1 == 1 ) return op2; else return (op1 & 1)*op2 + Mult( op1 >> 1, op2 << 1 ); }
Admin
Iterative Scheme:
Works with negative numbers and zeroes. I tried to follow the manual process as closely as possible :)
Admin
Python 3, 64 characters
Admin
I will add that many solutions here are making the same error.
Admin
public class SmallTest { public static void main(String [] args) { try { int m1 = Math.abs(Integer.parseInt(args[0])); int m2 = Math.abs(Integer.parseInt(args[1])); if (m1 > m2) {int temp = m1; m1 = m2; m2 = temp;} int result = 0; while (m1 >= 1) { if ((m1 & 1) > 0) result += m2; m1 >>= 1; m2 <<= 1; } System.err.println(args[0] + " * " + args[1] + " == " + result); } catch (Exception e) { System.err.println("Whoops: " + e.getMessage()); } } }
There you go. Even works for negative numbers ;) -- and it heavily optimizes... :)
Admin
Recursion is always the right answer!!
function peasantMath($a,$b) { return (($a>>1)%2 == 0 ? 0 : $b<<1) + ($a>>1 == 1 ? 0 : peasantMath($a>>1, $b<<1)); }
Also, TRWTF is that the link to esoteric languages is throwing database errors.
Admin
}
Admin
Oh wow, this is unbelievable. No trolls, no grammar nazis, no flame-bait, no spammers - just everyone chipping in on an interesting coding challenge. I think this is probably the most civilised comments page I've ever seen on TDWTF. Well done everyone, you've all earnt a cookie.
Admin
Admin
and only those who said their solution is "untested" have half an excuse... :)
Admin
Adjusted to handle negatives, and to handle an initial odd left operand, as pointed out above. This is PHP by the way, though it's not doing anything special.
CAPTCHA: nulla. mmmm, nulla wafers.
Admin
Using emacs lisp (and the dreaded recursion):
(defun russian-peasant-multiply (factor1 factor2) (cond ((eq factor1 1) factor2 ) ((eq (mod factor1 2) 0) (russian-peasant-multiply (/ factor1 2) (* factor2 2)) ) (t (+ factor2 (russian-peasant-multiply (/ factor1 2) (* factor2 2)))) ) )
Admin
Another assembly version, this time x64 using nasm
Admin
doesn't use any * or /, supports negative numbers:
#define NEGATE(x) (~(x) + 1)
int russian_multiplication(int a, int b) { short think_positive = 1; int result=0;
}
Admin
java.math.abs(int x)
if you use shifting operators, russion(Integer.MIN_VALUE, ...) will always end in an infinity loop if your loop condition depends on a value != 0
Admin
Damn: someone beat me to a C++ metaprogramming solution. This is easier to read:
Admin
Python 3.x Why else would they support unicode? Translation is probably hilariously wrong.
#Русский крестьянин умножения модуль
def Умножение(X,Y): пар = []
print(Умножение(18, 23))
Admin
RECURSIVE MAN SAYS:
def _mult(a,b): if a == 1: return [(a,b)] return [(a,b)]+_mult(a/2,b*2) def mult(a,b): return sum(b for (a,b) in _mult(a,b) if a%2==1)
I was trying to stick exactly to the algorithm. The intermediate list of numbers that you'd write down on paper is first produced by _mult. The list comprehension then crosses out which ones are unnecessary, and adds the rest.
Admin
python:
def rus(a,b): c = 0 while a > 0: a = a/2 b = b*2 if a % 2 != 0: c += b print 'total = ',c
Admin
Admin
Small improvement; now it really works with negative numbers...
public class SmallTest { public static void main(String [] args) { try { boolean n = args[0].trim().startsWith("-") ^ args[1].trim().startsWith("-"); int m1 = Math.abs(Integer.parseInt(args[0])); int m2 = Math.abs(Integer.parseInt(args[1])); if (m1 > m2) {int temp = m1; m1 = m2; m2 = temp;} int result = 0; while (m1 >= 1) { if ((m1 & 1) > 0) result += m2; m1 >>= 1; m2 <<= 1; } System.out.println(args[0] + " * " + args[1] + " == " + ((n && result != 0) ? "-" : "") + result); } catch (Exception e) { System.err.println("Whoops: " + e.getMessage()); } } }
Admin
Not very esoteric.... LOLCODE
HAI CAN HAS STDIO?
KTHXBYE
(captcha vulputate? sounds nasty!)
Admin
"It is said that Russian peasants multiply using a most curious method"
Is that why there are so many of them?
Admin
Minimalist C#
static int RussianMultiply(int a, int b) { int r=0; for (int i=a/2;i!=1;i--,a=a/2,b=b*2,r=r+(a%2)*b){} return r; }
Admin
Here's my very realistic solution, in C:
Admin
unsigned long long mult(unsigned long a, unsigned b) { unsigned long long acc = 0; while(a != 0) acc += (a%2)b,a/=2,b=2; return acc; }
Admin
This never terminates if x == 0.
My try:
Admin
a very horribly ruby one-liner:
def mul(a, b) (t=[[a, b]]).inject(0){|acc,(a, b)|a<=0?acc:acc+(t<<[a>>1,b<<1])[-2][1]*(a%2==1?1:0)} end
Admin
Best solution by far
Admin
Don't see anyone doing this for the adding portion: sum += b * (a & 1);
Save an if statement.
Admin
uint32 rpMultiply(uint32 a, uint32 b) { uint32 res = 0;
if (b < a) { // change for shorten time a = a ^ b; b = a ^ b; a = a ^ b; }
do { if (a & 1) { res += b; a >>= 1; b <<= 1; } while (a); } return res; }
Admin
In IA64 assembly:
Usable in C as: int russian_multiply(int num1, int num2);
Addendum (2009-07-22 10:26): cmp.eq not cmp.e. brainfart...
Admin
Python. Recursive, works with positive integers.
def mul(a,b): if a != 1: if a % 2 == 1: return b + mul(a >> 1, b << 1) else: return mul(a >> 1, b << 1) else: return b
Admin
Admin
You're doing it wrong. In the first example you forgot to add the 76 on the first row.
Admin