bramley.m@pg.com
Fri, 11 Sep 1998 8:16:00 -0400

Dear S+ers:

I took on the supplementary challenge by Bill Venebles, and have a quick two
liner for you that does the job:

factorize<-function(n) {
p<-rep(n,n)/(1:n)
p[trunc(p)==p]
}

Michael Bramley

Subject: Re: [S] factors (divisors ) of an integer
Author: (INTERNET)owner-s-news@wubios.wustl.edu at external
Date: 9/10/98 7:32 AM

> Dear all,
> I wonder whether there is an already built in Splus function to
find
> the divisors of a given integer, if so could you please point it out to
> me.
> Or if someone has already written such a function, could you
> please pass it over, if possible.
>
>
> The function I am looking for works sth like this
>
> N <- 6
> DN <- DIV(N)
> DN
> 1 2 3 6
>
> Thanks a lot,
> Mona

This turns out to be a pretty little programming exercise.
Here's a vectorized version, even, although it only returns the
*prime* divisors, not all the devisors. That a supplmentary
exercise...

-----------------------------------------------------------------
> factorize <- function(n) {
if(!is.numeric(n))
stop("cannot factorize non-numeric arguments")
if(length(n) > 1) {
l <- list()
for(i in seq(along = n))
l[[i]] <- Recall(n[i])
return(l)
}
if(n != round(n) || n < 2)
return(n)
tab <- 2:n
fac <- numeric(0)
while(n > 1) {
while(n %% tab[1] == 0) {
fac <- c(fac, tab[1])
n <- n/tab[1]
}
tab <- tab[tab <= n]
omit <- tab[1] * c(1, tab[tab <= n/tab[1]])
tab <- tab[ - match(omit, tab, nomatch = 0)]
}
fac
}
> factorize(6)
[1] 2 3
> factorize(4:8)
[[1]]:
[1] 2 2

[[2]]:
[1] 5

[[3]]:
[1] 2 3

[[4]]:
[1] 7

[[5]]:
[1] 2 2 2
-----------------------------------------------------------------

Over to you, Mona...

```--
_________________________________________________________________
Bill Venables, Head, Dep't of Statistics,   Tel.: +61 8 8303 5418
The University of Adelaide,                 Fax.: +61 8 8303 3696