Search code examples
pythonmultiplication

How to write a function/procedure that multiply 2 natural numbers without * operator?


So I was given a computer science problem to write a function which accepts two natural numbers and returns their product. The rules are that I am only allowed to use the addition of 1 (variable + 1), assigning and comparison operation. I end up with this code in python:

def multiplication_of_ab(a, b):
    placeholder = 0
    result = 0
    for counter in range(b):
        while (placeholder < a):
            placeholder += 1
        result += placeholder
        placeholder = 0
    return result

if __name__ == "__main__":
    print(mulitplication_of_ab(3, 4))

Maybe there is a solution that better fills the conditions?


Solution

  • Since it says "only comparisons", I assume that range is not allowed - fortunately, you can do the same thing with a while loop. (I guess while loops are allowed...) So, this code:

    for i in range(5):
        print(i)
    

    Can be re-written as:

    i = 0
    while i < 5:
        print(i)
        i += 1
    

    So here is the multiply function:

    def multiply(a, b):
        answer = 0
        i = 0
        # loop `a` times
        while i < a:
            j = 0
            # loop `b` times
            while j < b:
                # this line gets run `a * b` times
                answer += 1
                j += 1
            i += 1
        return answer