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 int开发者_C百科eresting 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)]
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.
The numbers of the form of 2^(n-1)*(2^n -1) are perfect numbers if 2^n - 1 is prime
#include<stdio.h>
#include<math.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long int n,i,sum= -n;
scanf("%lld",&n);
for(i=1;i<=sqrt(n);i++)
{
if(n%i==0)
sum = sum + i + n/i;
}
printf("%lld\n",sum);
}
return 0;
}
~
精彩评论