Re: [S] factors (divisors ) of an integer

Bill Venables (wvenable@attunga.stats.adelaide.edu.au)
Thu, 10 Sep 1998 21:02:20 +0930


> 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
South AUSTRALIA.     5005.   Email: Bill.Venables@adelaide.edu.au
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news