views:

92

answers:

1

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)]
+4  A: 

What you're looking for are called perfect numbers (sum of proper divisors equals the number itself).

If you're looking to improve the approach itself, see here.

To find proper divisors you should improve, as a start like this :

  • Your loop can stop at sqrt(max)
  • And every time you find a divisor i, max/i is a divisor too unless max/i == i then it should not be counted.
Soufiane Hassou
Also, you can start by discarding odd numbers (see link in my comment to the question)
nico
You may also be interested in the Wikipedia on perfect numbers, which links to a list of known perfect numbers (up to 25,956,377 digits).
nullglob