Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to determine proper divisors

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)]
like image 897
Chase Avatar asked Jun 29 '10 00:06

Chase


1 Answers

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.
like image 84
Soufiane Hassou Avatar answered Sep 27 '22 02:09

Soufiane Hassou