Christopher Yau Christopher Yau - 9 months ago 25
R Question

Write a function in R to find perfect numbers

I am a beginner in R and am attempting the following question:

Create a function in R which takes as its
input a natural number N and returns as an output the list of
all perfect numbers between 1 and N.

There are 3 steps here:
1. Check the list of factors
2. Check whether it is a perfect number
3.check from 1 to 10000

factorlist<-function(n){
if(n<2){return("Invalid Input")}
if(n%%1!=0){return("Invalid Input")}
vec<-0
for(i in 1:(n-1)){
if(n%%i==0){
vec[length(vec)]<-i
vec<-c(vec,0)
}
}
vec<-vec[-length(vec)]
return(vec)
}

perfectcheck<-function(n){
if(n-sum(factorlist(n)) ==0) {return("Perfect Number")}
else{return("Not Perfect Number")}
}



perfectcheckN<-function(N){
for(i in 1:N){
if(perfectcheck(i)=="Perfect Number"){
vec[length(vec)]<-i
vec<-c(vec)
}
}
vec<-vec[-length(vec)]
return(vec)
}


and i got the following error for my third step

Error in sum(factorlist(n)) : invalid 'type' (character) of argument


I spent like few hours and still could not figure out my mistake, please help. Thanks!

Answer Source

The output of factorlist(i) is character when i==1.

There's a lot of loops and ifs in your code. You can just do

facs <- function (x) {
    x   <- as.integer(x)
    div <- seq_len(abs(x) - 1L)
    div[x%%div == 0L]
}


perfectcheckN <- function(N){
    out <- 1:N
    out[sapply(out, function(x) x == sum(facs(x)))]
}