multiply two numbers by only using the subtract method in go

Here's an implementation of multiplying two numbers using only subtraction in Go:

main.go
func multiply(a, b int) int {
    result := 0
    for b != 0 {
        if b%2 == 1 {
            result = result + a
        }
        a = a * 2
        b = b / 2
    }
    return result
}
189 chars
12 lines

This function uses the Russian Peasant algorithm to determine the product of a and b. The algorithm reduces the multiplication to a series of additions and subtractions.

To use this function, simply call multiply(a, b), replacing a and b with the numbers you want to multiply.

gistlibby LogSnag