Check Friendly Pair in Python

Check whether two numbers form a friendly pair (same abundancy index).

IntermediateConditional ProgramsExample 14 of 20
check-friendly-pair.py
1# Program to check friendly pair
2
3def abundancy_index(n: int) -> float:
4 total = 0
5 for i in range(1, n + 1):
6 if n % i == 0:
7 total += i
8 return total / n
9
10a = int(input("Enter first number: "))
11b = int(input("Enter second number: "))
12
13if a <= 0 or b <= 0:
14 print("Numbers must be positive.")
15else:
16 if abundancy_index(a) == abundancy_index(b):
17 print(a, "and", b, "form a friendly pair")
18 else:
19 print(a, "and", b, "do not form a friendly pair")

Output

Enter first number: 6
Enter second number: 28
6 and 28 form a friendly pair

What's going on

Two numbers are friendly if the ratio (sum of divisors / number) is equal for both.

We implement a helper function to compute the abundancy index and compare for the two inputs.

After this program

If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.