user1464878
user1464878

Reputation:

How to find the common factors of 2 numbers

Print the number of common factors of a and b.

input > 10, 15

Output > 2

The common factors of 10, 15 are 1 and 5

My code

def print_factors(x,y):
l = []
for i in range(1, x + 1):
    if x % i == 0:
        l.append(i)
m = []
for i in range(1, y + 1):
    if y % i == 0:
        m.append(i)
print (list(set(l).intersection(m)))
num1 = int(input("Enter a number: ")) #10
num2 = int(input("Enter a number: ")) #15
print_factors(num1,num2)

Is there any better way to optimize, like list comprehension. or using zip module

Upvotes: 1

Views: 20274

Answers (2)

tevemadar
tevemadar

Reputation: 13205

Apparently GCD is there already, so the other answer could be modified as

from fractions import gcd
def cf(num1,num2):
    n=[]
    g=gcd(num1, num2)
    for i in range(1, g+1): 
        if g%i==0: 
            n.append(i)
    return n

print(cf(int(input("a:")),int(input("b:"))))

Then of course you can use the "trick" from prime-tests, and loop until the square root of the number only, as divisors come in pairs:

from fractions import gcd
from math import sqrt
def cf(num1,num2):
    n=[]
    g=gcd(num1, num2)
    for i in range(1, int(sqrt(g))+1):
        if g%i==0:
            n.append(i)
            if g!=i*i:
                n.append(int(g/i))
    return n

print(cf(int(input("a:")),int(input("b:"))))

Upvotes: 6

Shijith
Shijith

Reputation: 4872

to find the factors which are common for two numbers , do

def cf(num1,num2):
    n=[]
    for i in range(1, min(num1, num2)+1): 
        if num1%i==num2%i==0: 
            n.append(i)
    return n

print(cf(6,12))

>> output [1, 2, 3, 6]

edit: if you want the number of common factors

print(len(cf(6,12)))
>> output 4

Upvotes: 4

Related Questions