Hi all,
I am interested in finding the numbers that exhibit the property of having the sum of their proper divisors equal to the number. The first example is 6, where the proper divisors are 1 + 2 + 3 = 6.
I wrote the following code in R, but I feel it is pretty inefficient and can be improved upon significantly.
propDivisor <- function(
max
)
{
n<-{}
for(j in 2:max){
m<-{}
for(i in 1:(j/2+1)){
if(j%%i==0){m<-c(m,i)}
}
if(sum(m)==j){n<-c(n,j)}
}
return(cat("The proper divisors between 1 and", max, "are", n, ".", sep=" ") )
}
Does anyone have any suggestions for improving the following code? I feel one of the apply functions should be used here. Maybe this would be a decent code golf exercise for the future?
And as I know this comes up somewhat frequently here, this is NOT a homework problem, just something a coworker posed as an interesting coding challenger earlier today.
UPDATE:
Thanks to everyone for your comments and thoughts on places to look for further information. Here's another solution that utilizes sapply:
D <- function(n) sum((1:(n-1))[n%%1:(n-1)==0])==n
(2:9000)[sapply(2:9000,D)]