Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore
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.
The post Euler Problem 21: Amicable Numbers appeared first on The Devil is in the Data.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.