编写一个函数来计算R中的除数

SWR*_*SWR 0 r function

我试图在R中编写一个简单的函数来计算一个数的所有除数.这就是我想要输出的方式:

> divisors(21)
[1] 1 3 7 21
Run Code Online (Sandbox Code Playgroud)

我是初学者,从下面的代码开始.但是我觉得它完全错了,因为它根本不起作用.

divisors <- function(number) {
  x <- c(1:number)
  for(i in 1:number){
    if(number/i == c(x)) {
      paste(i)
    }
  }
  return(i)
}
divisors(10)
Run Code Online (Sandbox Code Playgroud)

Sim*_*lon 10

这个怎么样...

divisors <- function(x){
  #  Vector of numberes to test against
  y <- seq_len(x)
  #  Modulo division. If remainder is 0 that number is a divisor of x so return it
  y[ x%%y == 0 ]
}

divisors(21)
#[1]  1  3  7 21

divisors(4096)
#[1]    1    2    4    8   16   32   64  128  256  512 1024 2048
Run Code Online (Sandbox Code Playgroud)

当然,数字越大,效率就越重要.您可能希望替换seq_len(x)为......

seq_len( ceiling( x / 2 ) )
Run Code Online (Sandbox Code Playgroud)

而这只是为了与正数自然数一起使用.

更新:暂且使用Rcpp

#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
IntegerVector divCpp( int x ){
  IntegerVector divs = seq_len( x / 2 );
  IntegerVector out(0);
  for( int i = 0 ; i < divs.size(); i++){
    if( x % divs[i] == 0 )
      out.push_back( divs[i] );
  }
  return out;
}
Run Code Online (Sandbox Code Playgroud)

给出相同的结果:

identical( divCpp( 1e6 ) , divisors( 1e6 ) )
#[1] TRUE
Run Code Online (Sandbox Code Playgroud)

针对基本R函数运行...

require( microbenchmark )
bm <- microbenchmark( divisors(1e6) , divCpp(1e6) )
print( bm , unit = "relative" , digits = 3 , order = "median" )

#Unit: relative
#            expr  min   lq median   uq  max neval
#   divCpp(1e+06) 1.00 1.00   1.00 1.00  1.0   100
# divisors(1e+06) 8.53 8.73   8.55 8.41 11.3   100
Run Code Online (Sandbox Code Playgroud)