Check Friendly Pair in Python
Compare 6 and 28 through their divisor-sum ratios in Python. An introductory helper-function exercise explains friendly numbers and the limits of float equality.
1# Program to check friendly pair23def abundancy_index(n: int) -> float:4 total = 05 for i in range(1, n + 1):6 if n % i == 0:7 total += i8 return total / n910a = int(input("Enter first number: "))11b = int(input("Enter second number: "))1213if 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
6 and 28 form a friendly pair
The indices are 12/6 and 56/28, so both evaluate to 2.0 in this sample.
In this one
- Include all positive divisors
- Return a helper-function result
- Recognize float limits in ratio equality
How it works
- 1
Define abundancy_index to sum divisors from 1 through n.
- 2
Read a and b and reject non-positive values.
- 3
Compare their computed indices and print the pair result.
Edge cases
Same input twice
Enter 6 and 6.
The indices match; this implementation does not require distinct numbers.
Zero input
Enter 0 for either value.
The outer guard avoids calling the helper with a zero denominator.
What's going on
The abundancy index is the sum of all positive divisors divided by the number. Unlike the perfect-number lesson, this sum includes the number itself. For 6 the ratio is 12/6; for 28 it is 56/28. Both equal 2.
abundancy_index loops through n inclusively and returns that ratio. The outer check rejects non-positive arguments before the helper can divide by n. The two returned values are then compared to choose a message.
This simple helper returns a float. Two genuinely different rational ratios can round to the same float for sufficiently large inputs, so do not treat it as an exact number-theory implementation. An exact extension would compare integer cross-products of divisor sums. The code also accepts identical inputs, although friendly pairs are usually described as distinct numbers.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does this divisor sum include n?
Pick an answer to check it.
Question 2
Why do 6 and 28 match?
Pick an answer to check it.
Questions people ask
Does this divisor sum include n?
Yes. range(1, n + 1) includes the number when computing its abundancy index.
Why do 6 and 28 match?
Their divisor sums are 12 and 56, giving the same index 2.
How could the equality check be made exact?
Keep divisor sums as integers and compare sum_a * b with sum_b * a instead of rounded ratios.