Write a function in R to find perfect numbers

喜你入骨 提交于 2020-01-07 02:34:08

问题


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!


回答1:


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)))]
}


来源:https://stackoverflow.com/questions/42724735/write-a-function-in-r-to-find-perfect-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!