perform multiplication using only subtraction in python

To perform multiplication using only subtraction in python, we can simply create a function that takes two arguments, a and b, and iteratively subtracts the value of a from the product of a and b until the value of b becomes zero. The result of the function is the final value of a, which is the product of the original values of a and b.

Here's the code:

main.py
def multiply_using_subtraction(a, b):
    product = 0
    while b > 0:
        product -= a
        b -= 1
    return -product
127 chars
7 lines

We can test the function using the following code:

main.py
a = 6
b = 8
product = multiply_using_subtraction(a, b)
print(f"{a} * {b} = {product}")
87 chars
5 lines

This will output:

main.py
6 * 8 = 48
11 chars
2 lines

Note that while this approach works, it is not the most efficient way to perform multiplication in python. It is generally better to use the built-in * operator or the numpy library for more complex operations.

gistlibby LogSnag