r - 错误结果向量太长

标签 r function prime-factoring

我试图编写一个函数来显示数字的素因数。这就是我得到的

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/

相关文章:

r - ggplot2 : altering x and y grid lines 中的主题操作

r - broom::tidy 多项式回归失败

r - 使用带有符号链接(symbolic link)文件的 read.csv

python - 在 Cython 的 cdef 语句中使用 scipy.integrate.quad?

python - 寻找最大质因数的正确算法

c++ - C 或 C++ : Libraries for factoring integers?

Python:错误的输出和 ValueError:素因数创建者

r - 在 Azure Databricks 上安装 rgdal 和 rgeos

c - 替换 C 中的函数定义

function - 从 Matlab 中的其他工作区访问变量?