f(a, b);
the obvious way to multply integers is simply to add a to itself b-1 times. The algorithm below, however, adds a shifted i times to the left if b is odd (b & 0x01 == 1), where i is a number from 0 (beginning) to whatever. After every iteration, shift b to the right, lather, rinse, repeat until no more b. Keep in mind, for all i know, i could be the first person to use this, or this may be common knowledge already. I really don't know. thought i'd post it and see what you all thought.
sub multiply { ($a, $b) = @_; $i=0; $product=0; do { $product += ($a << $i) if ($b & 0x01); $i++; } while ($b>>=1); return $product; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 1: Fast Multiplication
by tilly (Archbishop) on Jan 09, 2001 at 19:56 UTC | |
by zencrypt (Novice) on Jan 12, 2001 at 14:09 UTC | |
by tilly (Archbishop) on Jan 12, 2001 at 17:34 UTC | |
by zencrypt (Novice) on Jan 13, 2001 at 10:36 UTC | |
|
Slow Multiplication
by I0 (Priest) on Jan 10, 2001 at 01:55 UTC |