code-golf – numbers and your friends

Question:

The sum of all the natural number (positive integer) of divisors 220, except 220, is equal to:

1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284

And the sum of all the natural number of divisors 284, except itself, is equal to:

1 + 2 + 4 + 71 + 142 = 220

The numbers 220 and 284 are called friends . Generally, we say that two positive integers are friends if each of the sum of their divisors (excluding the number itself) equals the other number.

Write the program to calculate all friends numbers 2 to N.

Example:

If the input is N = 1500 the output should be: (284, 220) , (1210, 1184)

Note: Use the language you prefer.

Answer:

Python (115 bytes)

N,d=1500,lambda n:sum(i for i in range(1,n) if n%i==0)
print({i:d(i) for i in range(N+1) if i==d(d(i)) and i>d(i)})

Exit:

{284: 220, 1210: 1184}

Explanation:

The first line defines the values ​​of N , 1500, and d , a lambda function that calculates the sum of the divisors of an n value. In turn, the second line uses the syntax of dict comprehension , returning the pair i: d(i) for every value of i that is equal to d(d(i)) and that is greater than d(i) , in the range defined by range(2,N+1) . The condition i>d(i) already eliminates the duplicated pairs, such as (284, 220) and (220, 284) and pairs composed of perfect numbers, such as (6, 6) and (28, 28) , which satisfy the condition i == d(d(i)) .

See working on Ideone .

Scroll to Top