我试图编写一个函数来显示数字的素因数。这就是我得到的
unipri<- function (n) {
q<- NULL
for (i in 1:n){if (n%%i==0) p<- c(p, i) }
q<- c(1 ,apply(as.matrix(p), 1,function(c) ifelse(all(c%%(2:(c-1))!=0),c,1)))
q<- q[!duplicated(q)]
return (q)
}
当我给它一个值时,例如:600851475143,我收到错误消息
"Error in 1:n : result would be too long a vector"
有什么建议吗,还有更紧凑的方式来编写代码吗?
最佳答案
更有效的因式分解方法是递归进行。这是一个例子。
factorise <- function(a,n){ #need 'a' as a cumulative answer in order to retain on recursion. Initially null.
if(n<4){
a <- c(n,a)
} else {
maxtest <- floor(sqrt(n)) #highest possible divisor
odds <- floor(maxtest/2) #number of odd factors to test
totest <- c(2,2*seq_len(odds)+1) #list of possible factors
i <- 1
fac <- FALSE
while(!fac & i<=length(totest)){
fac <- (n %% totest[i] == 0) #found a divisor
if(fac) a <- Recall(c(totest[i],a),n/totest[i]) #recursive bit
i <- i+1
}
if(!fac) a <- c(n,a)
}
return(a)
}
factors <- function(n) {
sort(factorise(numeric(0),n))
}
factors(600851475143)
[1] 71 839 1471 6857
关于r - 错误结果向量太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498699/