code to return divisors and compare common ones

Asked

Viewed 1,276 times

0

I am trying to create a code that returns the common divisors between 2 variables that receive integer numbers. And then show the common divisors.

To return me the splitters I am using this code for testing:

import numpy as np

def divisores(num):

n = np.arange(1,num)

d = num % n

zeros = d == 0

print (n[zeros])

divisores(30) 

But I need this function to return me the 2-value dividers and not just one. Besides comparing the common divisors between them, because I couldn’t think of a way to do.

3 answers

4

We can make the solution a little more general. Let’s imagine that we can define a limitless amount of values to determine the common divisors between them. We can do this through function:

def divisores(*numeros):
    ...

So if we want the common divisors of 5 and 10, we can call divisores(5, 10), and if we want the divisors 42, 100 and 999, just call divisores(42, 100, 999). If we consider, for example, entry 42, 100 and 999, it is easy to see that all common divisors of the three numbers will be divisor of each number individually, which implies that all divisors must be less than or equal to the lower of the input values, because it has as a value greater than 42 to be divisor of 42. Thus, we know that it is enough to go through all the values between 1 and the lowest entry value:

def divisores(*numeros):
    menor = min(numeros)
    for i in range(1, menor+1):
        ...

And to define whether i is divisor of all input numbers, we can use the function all and check if the rest of the breakdown of all input numbers by i is 0.

def divisores(*numeros):
    menor = min(numeros)
    for i in range(1, menor+1):
        if all(numero % i == 0 for numero in numeros):
            yield i

With the yield return a generator that iterates over the divisors of all input numbers.

print('Divisores de 5 e 10:', list(divisores(5, 10)))  # [1, 5]
print('Divisores de 42, 100 e 999:', list(divisores(42, 100, 999)))  # [1]
print('Divisores de 14, 38 e 74:', list(divisores(14, 38, 74)))  # [1, 2]

See working on Repl.it | Ideone

2

Taking advantage of the function you have to calculate the dividers, you are a little short to complete the problem. In order to be able to re-use the function that has the best option is to transform the print in a return:

def divisores(num):
    n = np.arange(1,num)
    d = num % n
    zeros = d == 0
    return n[zeros]

In fact it is always better to do this because it makes the function can be used anywhere without having to force a writing.

Now just build a function that takes two numbers, call the divisores for each of these numbers and get the common numbers of each set. There are many ways to get the common numbers of each set and I will opt for the intersection of set:

def divisores_comuns(num1, num2):
    divs1 = set(divisores(num1)) # obtendo os divisores e transformando em set
    divs2 = set(divisores(num2)) # obtendo os divisores e transformando em set
    return divs1 & divs2 # & é a intereseção de dois sets

See this code working on Ideone

  • Well, I would use that. The approach is more objective and more polished.

0

Ana,

To receive two values, one must either consider N as a list of integers, or receive two arguments in the function signature, such as:

def divisores(num1, num2):

Although your procedure works, notice the following:

  1. You test the division of all numbers between 0 - received number, even if the smallest possible division (2), happens in num/2;
  2. You test, again, every numpy array if the rest of the split is 0;

Although it’s not a very charming algorithm, one way you perform fewer iterations is as follows::

div_1 = set() #Cria um set vazio
for i in range(1, int(num1/2+1)): #itera de 1 até metade do valor numérico
    if num1%i == 0: #testa se mod é zero.
        div_1.add(i) #anexa o valor de i ao set de divisores do primeiro numero

It is worth remembering that this function, like its code, does not return the value itself as a possible divisor (in this case, when you enter 30, the values obtained will be:{1, 2, 3, 5, 6, 10, 15} ) (30 Excluso). In addition, it is possible to consider using the "set" object instead of lists, since the numbers should not repeat.

In this case, if the final function were just to find the intersection of the common division values, you could include everything in the same loop, as it is not, a simplistic approach is to run another iteration on to identify the same divisors of the other number (num2).

For the intersection, you could accomplish the following:

lista_divisores_comuns = div_1.intersection(div_2)

The final code would look like:

def divisores(num1, num2):    
    div_1 = set()
    div_2 = set()
    for i in range(1, int(num1/2+1)):
        if num1%i == 0:
            div_1.add(i)

    for i in range(1, int(num2/2+1)):
        if num2%i == 0:
            div_2.add(i)


    lista_divisores_comuns = div_1.intersection(div_2)

    return div_1, div_2, lista_divisores_comuns

Browser other questions tagged

You are not signed in. Login or sign up in order to post.