How can a function return if a number is a factor of another?

1.1k views Asked by At

I'm writing a function for Python 3.7.3 that tests if a number is a factor of another number.

I tried researching on the internet to find some idea about how the write a function that tests the validity of factoring two unknown real numbers. I ended up stumbling upon the difference between factoring and divisibility, which intrigued me somewhat.

def is_factor(f, n):
    """This function returns if f, a real number, is a factor of another
    real number n."""
    while f * f <= n:
        if f % n == 0:          
            f /= n
            #return True?
        else: f += 1 #return False?

print(is_factor(1, 15))

The function appears to work, because Python returns None, and that's all. I expect the function to return a True or False solution. There must be some logical error in the code. Any feed back is appreciated.

1

There are 1 answers

2
Gilles-Philippe Paillé On

If you are dealing with integers, use:

def is_factor(f, n):
    return n%f==0

If you are dealing with real numbers, the above code works but is very sensitive to floating point imprecision. Instead, you can divide n by f and see if you get back n after rounding to the nearest integer:

def is_factor(f, n, e):
    return abs(round(n/f)*f-n)<e