**Tony's bubble universe » R**, and kindly contributed to R-bloggers)

Officially, it’s weekend. I’m solving this 23rd Euler problem just before my supper.

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number

nis called deficient if the sum of its proper divisors is less thannand it is called abundant if this sum exceedsn. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

This is a long-written problem. But once been understood, the solution is very straightforward. First is to find all the abundant numbers; then combine each pair of them to gather the sums of two abundant numbers; and discard them from the numbers below 28123 and sum the rest up. I’ll need the DivisorsSearch() implemented in the post before the last to calculate the divisors for a certain number.

^{?}View Code RSPLUS

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# search for abundant numbers num.lst <- 1:28123 flags <- logical(length(num.lst)) for (i in 1:length(num.lst)) { divisors.sum <- sum(DivisorsSearch(i)) flags[i] <- (divisors.sum > i) } num.abundant <- num.lst[flags] # calculate the sum of those sums of the abundant numbers len <- length(num.abundant) sums <- matrix(0, nrow = len, ncol = len, dimnames = list(num.abundant, num.abundant)) for (i in 1:(len - 1)) { for (j in i:len) { sums[i, j] <- sum(num.abundant[c(i, j)]) } } sums <- unique(as.vector(sums)) sums <- sums[sums <= 28123] result <- sum(num.lst) - sum(sums) cat("The result is:", result, "\n") |

**leave a comment**for the author, please follow the link and comment on their blog:

**Tony's bubble universe » R**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...