Multiplication in Python ― without actually multiplying!

This is just something interesting I wrote last year. It will multiply two integers using an algorithm which is sometimes called “russian peasant multiplication”.

def peasant_multiply(a, b):
    '''Multiply the floor of 'a' and 'b' using only addition, bitshifts, and the binary AND operator.'''
    a = int(a)
    b = int(b)
    product = 0
    while a > 0:
        if a & 1:
            product = product + b
        a = a >> 1
        b = b << 1
    return product

Leave a Reply