Skip to content
Prev 177992 / 398502 Next

large factorials

if you really really need to have it done from within r, you may want to
use an external facility such as bc, the 'basic calculator' [1,2].  for
example, use the (experimental!) r-bc:

    source('http://r-bc.googlecode.com/svn/trunk/R/bc.R')

(you can also download the zipped package which will install on windows,
where you're likely not to have bc yet; see
http://code.google.com/p/r-bc/downloads/)

    # an intuitive but slow approach implemented mostly in r
    # (alternatively, you may want to have it recursive)
    factorial.r = function(n) {
       result = bc(1)
       while (n > 1) {
          result = result*n
          n = n-1 }
       result }

    # an alternative, faster approach implemented mostly in bc
    factorial.bc = function(n)
       bc(sprintf('define fact(n) { if (n < 2) return 1; return n *
fact(n-1) }; fact(%d)', n))

    library(rbenchmark)
    benchmark(replications=10, columns=c('test', 'elapsed'),
       r=factorial.r(500),
       bc=factorial.bc(500))

    #   test elapsed
    # 2   bc   0.101
    # 1    r  34.181

this gives you factorials for arbitrary input, but note that the result
is not an integer, but an object of class 'bc' backed by a *character
string*:

    result = factorial.bc(10^4)
    is(result)
    # "bc"
    nchar(result)
    # 35660

vQ


[1] http://www.gnu.org/software/bc/manual/html_mono/bc.html
[2] http://www.opengroup.org/onlinepubs/9699919799/utilities/bc.html
Murray Cooper wrote: