Home > Back-end >  Subtraction in place of Division: How to approximate division with subtraction
Subtraction in place of Division: How to approximate division with subtraction

Time:09-03

I want to do division but with subtraction. I also don't necessarily want the exact answer. No floating point numbers too (preferably) How can this be achieved? Thanks in advance:)

Also the process should almost be as fast as normal division.

CodePudding user response:

to approximate x divided by y you can subtract y from x until the result is smaller or equal to 0 and then the result of the division would be the number of times you subtracted y from x. However this doesn't work with negatives numbers.

CodePudding user response:

Well, let's say you have your numerator and your denominator. The division basically consists in estimating how many denominator you have in your numerator.

So a simple loop should do:

def divide_by_sub(numerator, denominator):

    # Init
    result = 0
    remains = numerator
    
    # Substract as much as possible
    while remains >= denominator:
        remains -= denominator
        result  = 1
    
    # Here we have the "floor" part of the result
    return result

This will give you the "floor" part of your result. Please consider adding some guardrails to handle "denominator is zero", "numerator is negative", etc.

My best guess, if you want go further, would be to then add an argument to the function for the precision you want like precision and then multiply remains by it (for instance 10 or 100), and reloop on it. It's doable recursively:

def divide_by_sub(numerator, denominator, precision):

    # Init
    result = 0
    remains = numerator

    # Substract as much as possible
    while remains >= denominator:
        remains -= denominator
        result  = 1

    # Here we have the "floor" part of the result. We proceed to more digits
    if precision > 1:
        remains = remains * precision
        float_result = divide_by_sub(remains, denominator, 1)
        result  = float_result/precision

    return result

Giving you, for instance for divide_by_sub(7,3,1000) the following:

2.333

  • Related