perform multiplication using only subtraction in go

We can perform multiplication using only subtraction in Go by iteratively subtracting the second number from the first number and keeping count of the number of subtractions. The count will be the product of the two numbers.

Here's the code:

main.go
func multiply(x, y int) int {
    if x == 0 || y == 0 {
        return 0
    }

    result := 0
    for i := 1; i <= y; i++ {
        result += x
    }

    return result
}
173 chars
13 lines

In this code, we first check if either of the numbers is 0, in which case the product would be 0. Then we initialize the result to 0 and iterate from 1 to the second number. In each iteration, we add the first number to the result. Finally, we return the result as the product of the two numbers.

gistlibby LogSnag