Euler problem 21 takes us to the realm of amicable numbers, which are listed in sequence A259180 in the OEIS. Amicable, or friendly, numbers are the most romantic numbers known to maths. Amicable numbers serve absolutely no practical purpose, other than mathematical entertainment.

A related concept is a perfect number, which is a number that equals the sum of its proper divisors. Mathematicians have also defined sociable numbers and betrothed numbers which are similar to amicable numbers. But perhaps these are for another Euler problem.

## Euler Problem 21 Definition

Let be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If and , where , then and are an amicable pair and each of and are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore . The proper divisors of 284 are 1, 2, 4, 71 and 142; so, .

Evaluate the sum of all the amicable numbers under 10000.

# Solution

The first part of the code provides for a function to list all proper divisors for a given integer *x*. The loop determines the divisors for the numbers 220 to 10,000, calculates their sum and then checks if these numbers are amicable. When the code finds an amicable number, the counter jumps to the sum of the divisors to check for the next one.

proper.divisors <- function(x) { divisors <- vector() d <- 1 for (i in 1:floor(sqrt(x))) { if (x %% i == 0) { divisors[d] <- i if (i != x/i) { d <- d + 1 divisors[d] <- x / i } d <- d + 1 } } return(divisors) } answer <- 0 n <- 220 while (n <= 10000) { div.sum <- sum(proper.divisors(n)) - n if (n == sum(proper.divisors(div.sum)) - div.sum & n != div.sum) { answer <- answer + n + div.sum print(paste0("(", n, ",", div.sum, ")")) n <- div.sum } n <- n + 1 } print(answer)

Amicable numbers were known to the Pythagoreans, who credited them with many mystical properties. Before we had access to computers, finding amicable numbers was a task that required a lot of patience. No algorithm can systematically generate all amicable numbers, and until 1946 only 390 pairs were known. Medieval Muslim mathematicians developed several formulas to create amicable numbers, but the only way to be complete is using brute force.