Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
In this lesson we will make a program on friendly numbers in Python, in order to practice with iterative structures.
Recall that two numbers are said to be friendly if the sum of the divisors proper to one, but excluding the number itself, is equal to the other number and vice versa.
For example, numbers 220 and 284 are friendly.
In fact, the divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110. Their sum gives me 284.
Similarly we find the divisors of 284: 1, 2, 4, 71, 142 which sum makes 220.
So the numbers are friendly.
Friendly numbers – algorithm in Python
The solution algorithm therefore consists in finding all the divisors of the first number, excluding the number itself, adding them and comparing them with the other number. Similarly with the second number.
So first of all we take the two integers as input and store them in two variables number_one and number_two. Then we initialize the variables div, sum1 and sum2.
The variable div represents the divisor and is initialized to 1 at the beginning and after the first while, because we will need it for the other number. Alternatively, another variable could be used.
After with the while loop we find all the divisors of the number_one and add them in the variable sum1. The same for the other number for which we add the divisors in the variable sum2.
Finally we compare sum1 with number_two and sum2 with number_one. If both equalities are true then the numbers are friendly, otherwise they are not.
Here is the complete code of the algorithm on friendly numbers in Python:
number_one = int(input('Enter the first number:')) number_two = int(input('Enter the second number:')) div, sum1, sum2 = 1,0,0 while div <= number_one / 2: if number_one % div == 0: sum1 += div div += 1 div = 1 # let's return the divisor to 1 while div <= number_two / 2: if number_two% div == 0: sum2 += div div += 1 if sum1 == number_two and sum2 == number_one: print ('The numbers are friendly!') else: print ('The numbers are not friendly!')
We could add a check, because in fact it is useless to find all the divisors of the second number, if sum1 is different from number2.
Therefore it would be appropriate to find the divisors of the second number only if the condition sum1 equal to number_two is satisfied.
Test the code in the online Python compiler in that link: Python compiler online.
We have created the same algorithm with Algobuild.
Clearly this is just one of the possible ways to implement the friendly numbers algorithm in Python, have your say in the comments below.
Some useful links
How to find the maximum of N numbers