Russian peasant multiplication
I learned this one from Intro to Algorithms.
- Q: How would you multiply two numbers without using the
*
operator? - A: Using the Russian peasant multiplication algorithm and bitshift operators.
Code
Some tests:
package mult
import "testing"
func TestMultNegative(t *testing.T) {
if v := Mult(-1, -4); v != 4 {
"Expected %v to be 4", v)
t.Fatalf(
}
}
func TestMultPositive(t *testing.T) {
if v := Mult(7, 9); v != 63 {
"Expected %v to be 63", v)
t.Fatalf(
}
}
func TestMultPositiveAndNegative(t *testing.T) {
if v := Mult(-8, 9); v != -72 {
"Expected %v to be -72", v)
t.Fatalf(
} }
Implementation:
package mult
func sign(x int) int {
if x < 0 {
return -1
}return 1
}
func abs(x int) int {
if x < 0 {
return -x
}return x
}
func Mult(a, b int) int {
// Handle the case with negative values for a and b
as := sign(a)
a = abs(a)
bs := sign(b)
b = abs(b)
// Actual multiplication
uint(a)
x := uint(b)
y := uint(0)
z := for x > 0 {
if x%2 == 1 {
uint(y)
z +=
}1
x >>= 1
y <<=
}return int(z) * as * bs
}
Pretty cool, huh?