VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pairs-amicable-numbers/

⇱ Pairs of Amicable Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pairs of Amicable Numbers

Last Updated : 21 Jan, 2025

Amicable numbers are pairs of two integers (a, b) such that:

  • Sum of the proper divisors of a = b and Sum of the proper divisors of b = a,

where a ≠ b.

Examples: (220,284)

  • Proper divisors of 220: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110
    • Sum = 1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284
  • Proper divisors of 284: 1, 2, 4, 71, 142
    • Sum = 1 + 2 + 4 + 71 + 142 = 220

Thus, (220, 284) is a pair of amicable numbers.

Some other examples include:

  • (1184, 1210)
  • (2620, 2924)
  • (5020, 5564)
  • (6232, 6368)

Example:

Input : arr[] = {220, 284, 1184, 1210, 2, 5}
Output : 2
Explanation : (220, 284) and (1184, 1210) form amicable pair.

Input : arr[] = {2620, 2924, 5020, 5564, 6232, 6368}
Output : 3
Explanation : (2620, 2924), (5020, 5564) and (6232, 6368) forms amicable pair.

A simple solution is to traverse each pair and check if they form an amicable pair, if they do we increment the count. 

Implementation:


Output
2
3

An efficient solution is to keep the numbers stored in a map and for every number, we find the sum of its proper divisor and check if that's also present in the array. If it is present, we can check if they form an amicable pair or not.

Thus, the complexity would be considerably reduced. Below is the C++ program for the same. 

Implementation:


Output
2
3

This article is contributed by Ashutosh Kumar

Comment
Article Tags:
Article Tags: