R函数返回所有因子 [英] R Function for returning ALL factors

查看:99
本文介绍了R函数返回所有因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的常规搜索foo使我失败.我正在尝试找到一个R函数,该函数返回整数的所有因子.至少有两个具有factorize()函数的软件包:gmp和conf.design,但是这些函数仅返回素数.我想要一个返回所有因素的函数.

My normal search foo is failing me. I'm trying to find an R function that returns ALL of the factors of an integer. There are at least 2 packages with factorize() functions: gmp and conf.design, however these functions return only prime factors. I'd like a function that returns all factors.

显然,这很难进行搜索,因为R具有一个称为factor的结构,该结构在搜索中会带来很多干扰.

Obviously searching for this is made difficult since R has a construct called factors which puts a lot of noise in the search.

推荐答案

要跟进我的评论(感谢@Ramnath为我的错字),暴力破解方法在我的64位8 gig机器上似乎相当有效:

To follow up on my comment (thanks to @Ramnath for my typo), the brute force method seems to work reasonably well here on my 64 bit 8 gig machine:

FUN <- function(x) {
    x <- as.integer(x)
    div <- seq_len(abs(x))
    factors <- div[x %% div == 0L]
    factors <- list(neg = -factors, pos = factors)
    return(factors)
}

一些例子:

> FUN(100)
$neg
[1]   -1   -2   -4   -5  -10  -20  -25  -50 -100

$pos
[1]   1   2   4   5  10  20  25  50 100

> FUN(-42)
$neg
[1]  -1  -2  -3  -6  -7 -14 -21 -42

$pos
[1]  1  2  3  6  7 14 21 42

#and big number

> system.time(FUN(1e8))
   user  system elapsed 
   1.95    0.18    2.14 

这篇关于R函数返回所有因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆