Multiply without multiply
C, 84 83 78 Characters
m;main(a,b){for(scanf("%d%d",&a,&b);a;b+=b)a&1?m+=b:0,a>>=1;printf("%d\n",m);}
In a more readable form
m;main(a,b)
{
scanf("%d%d",&a,&b);
while (a)
{
if (a&1)
m+=b;
a>>=1;
b+=b;
}
printf("%d\n",m);
}
The algorithm is better known as the Ethiopian Multiplication or the Russian Peasant Multiplication.Here’s the algorithm :
- Let the two numbers to be multiplied be a and b.
- If a is zero then break and print the result.
- If a is odd then add b to the result.
- Half a, Double b. Goto Step 2.
APL (5)
Takes input on standard input separated by newlines.
+/⎕⍴⎕
Golfscript - 12 characteres
~0\{1$+}*\;
Please note that *
here is not the multiplication operator, it's instead a repetition operator, see the second use here.