Debian Codegraph @

R/prime-numbers-fn.R

raw
1 ####---- Prime numbers, factorization, etc. --- "illustatration of programming"
2 ####---- Function definitions --------
3
4 ## for examples, see "../demo/prime-numbers.R"
5
6 ### MM: Currently only export primes() and factorize() ---- TODO: CLEAN UP!
7
8
9 ## NOTA BENE:
10 ## ---------
11 ## I found out [R 1.9.x, July 2004], that the primes() function
12 ## Bill Venables' "conf.design" package (== primes.() below) is almost an ordner of
13 ## magnitude faster than the primes.*() or prime.sieve() ones further below :
14 ## but read on: I'm improving it a bit:
15 primes. <- function(n) {
16 ## By Bill Venables <= 2001
17
18 ## Find all primes less than n (or max(n) if length(n) > 1).
19 ## Uses an obvious sieve method. Nothing flash.
20 ##
21 if ((M2 <- max(n)) <= 1)
22 return(numeric(0))
23 x <- 1:M2
24 x[1] <- 0
25 p <- 1
26 M <- floor(sqrt(M2))
27 while((p <- p + 1) <= M)
28 if(x[p] != 0)
29 x[seq(p^2, n, p)] <- 0
30 x[x > 0]
31 }
32
33 ##' New 'pSeq' is still (almost ?) always **slower** than pSeq = NULL !!!!
34 primes <- function(n, pSeq = NULL) {
35 ## Find all primes less than n (or max(n) if length(n) > 1).
36 ## Uses an obvious sieve method. Nothing flash.
37 ##
38 ## By Bill Venables <= 2001
39 ## MM: work with logical(), keep to integer --> another 40% speedier for R
40 ## --- 2016-01: replacing seq() by seq.int() in loop got another 20% !!
41 if ((M2 <- max(n)) <= 1)
42 return(integer(0))
43 n <- as.integer(M2)
44 if(is.null(pSeq)) {
45 P <- rep.int(TRUE, n)
46 P[1] <- FALSE
47 } else { ## assume pSeq = c(2, 3, 5, ..., P_max)
48 ## stopifnot(pSeq[1:2] == 2:3, !is.unsorted(pSeq))
49 if(!is.integer(pSeq)) pSeq <- as.integer(pSeq)
50 maxP1 <- pSeq[length(pSeq)] + 1L
51 if(maxP1 >= n)
52 return(pSeq)
53 ## else (maxP1 := max(pSeq) + 1) < n
54 P <- logical(maxP1) # all FALSE
55 P[pSeq] <- TRUE
56 P <- c(P, rep.int(TRUE, n - maxP1))
57 }
58 M <- as.integer(sqrt(M2))
59 ## p <- 1:1
60 ## while((p <- p + 1:1) <= M)
61 for(p in seq_len(M))
62 if(P[p])# p is prime, sieve with it
63 P[seq.int(p*p, n, p)] <- FALSE
64 seq_len(n)[P]
65 }
66
67
68 ## much slower than primes (even after improvement Jan.2016)
69 prime.sieve <- function(maxP = pM*pM, p2et = c(2,3,5))
70 {
71 ## Purpose: Produce ALL prime numbers from 2, 3.., using 2,3,5,7,...
72 ## -------------------------------------------------------------------------
73 ## Arguments: maxP : want primes up to maxP
74 ## p2et: primes c(2,3,5,..., pM);
75 ## -------------------------------------------------------------------------
76 ## Author: Martin Maechler, Date: 26 Jan 96, 15:08
77 if(any(p2et[1:2] != 2:3) || is.unsorted(p2et <- as.integer(p2et)))
78 stop("argument 'p2et' must contain SORTED primes 2,3,..")
79 k <- length(p2et)
80 pM <- p2et[k]
81 if(maxP <= pM+1L) p2et #- no need to compute more
82 else if((maxP <- as.integer(maxP)) > pM*pM)
83 prime.sieve(maxP, prime.sieve(pM*pM, p2et))
84 else { #-- pM < maxP <= pM^2
85 r <- seq.int(from = pM+2L, to = maxP, by = 2L)
86 for(pr in p2et[p2et <= sqrt(maxP)])
87 if(0 == length(r <- r[r %% pr != 0])) break
88 c(p2et,r)
89 }
90 }
91
92 factorize <- function(n, verbose = FALSE)
93 {
94 ## Purpose: Prime factorization of integer(s) 'n'
95 ## -------------------------------------------------------------------------
96 ## Arguments: n vector of integers to factorize (into prime numbers)
97 ## --> needs a primes() function [originally prime.sieve]
98 ## >> Better would be: Define class 'primefactors' and "multiply" method
99 ## then use this function recursively only "small" factors
100 ## -------------------------------------------------------------------------
101 ## Author: Martin Maechler, Date: 26--30 Jan 96
102 n <- if(all(n < .Machine$integer.max)) as.integer(n)
103 else {
104 warning("factorizing large int ( > maximal integer )")
105 round(n)
106 }
107 N <- length(n)
108 M <- as.integer(sqrt(max(n))) #-- check up to this prime number
109 ##-- for M > 100 to 200: should DIVIDE first and then go on ..
110 ##-- Here, I am just (too) lazy:
111 pr <- primes(M) # was: prime.sieve(maxP = M)
112 ## k <- length(pr)
113 nDp <- outer(pr, n, FUN = function(p,n) n %% p == 0) ## which are divisible?
114 ## dim(nDp) = (k,N) ;
115 ## Divide those that are divisible :
116 ## quot <- matrix(n,k,N,byrow=T)[nDp] %/% matrix(pr,k,N)[nDp]
117 ## quot <- rep(n,rep(k,N))[nDp] %/% rep(pr,N)[nDp]
118 res <- vector("list",length = N)
119 names(res) <- n
120 for(i in 1:N) { ## factorize n[i]
121 nn <- n[i]
122 if(any(Dp <- nDp[,i])) { #- Dp: which primes are factors
123 nP <- length(pfac <- pr[Dp]) # all the small prime factors
124 if(verbose) cat(nn," ")
125 } else { # nn is a prime
126 res[[i]] <- cbind(p = nn, m = 1L)
127 if(verbose) cat("direct prime", nn, "\n")
128 next # i
129 }
130 m.pr <- rep(1L, nP)# multiplicities
131 Ppf <- prod(pfac)
132 while(1 < (nn <- nn %/% Ppf)) { #-- have multiple or only bigger factors
133 Dp <- nn %% pfac == 0
134 if(any(Dp)) { # have more smaller factors
135 m.pr[Dp] <- m.pr[Dp] + 1L
136 Ppf <- prod(pfac[Dp])
137 } else { #-- the remainder is a bigger prime
138 pfac <- c(pfac,nn)
139 m.pr <- c(m.pr, 1L)
140 break # out of while(.)
141 }
142 }
143 res[[i]] <- cbind(p = pfac, m = m.pr)
144 } # end for(i ..)
145
146 res
147 }
148
149 test.factorize <- function(res)
150 {
151 ## Purpose: Test prime factorization
152 ## -------------------------------------------------------------------------
153 ## Arguments: result of factorize
154 ## -------------------------------------------------------------------------
155 ## Author: Martin Maechler, Date: 29 Jan 96, 10:29
156 n <- as.numeric(names(res))# as.integer() may fail for *large* ones
157 n == vapply(res, function(pf) prod(pf[,"p"] ^ pf[,"m"]), 1.)
158 }
159
160 ##- From: Bill Venables <[email protected]>
161 ##- Date: Thu, 10 Sep 1998 21:02:20 +0930
162 ##- To: mona kanaan <[email protected]>
163 ##- Cc: [email protected]
164 ##- Subject: Re: [S] factors (divisors ) of an integer
165 ##-
166 ##- > Dear all,
167 ##- > I wonder whether there is an already built in Splus function to find
168 ##- > the divisors of a given integer, if so could you please point it out to
169 ##- > me.
170 ##- > Or if someone has already written such a function, could you
171 ##- > please pass it over, if possible.
172 ##- >
173 ##- >
174 ##- > The function I am looking for works sth like this
175 ##- >
176 ##- > N <- 6
177 ##- > DN <- DIV(N)
178 ##- > DN
179 ##- > 1 2 3 6
180 ##- >
181 ##- > Thanks a lot,
182 ##- > Mona
183 ##-
184 ##- This turns out to be a pretty little programming exercise.
185 ##- Here's a vectorized version, even, although it only returns the
186 ##- *prime* divisors, not all the devisors. That a supplmentary
187 ##- exercise...
188
189 factorizeBV <- function(n) {
190 if(!is.numeric(n))
191 stop("cannot factorize non-numeric arguments")
192 if(length(n) > 1) {
193 l <- list()
194 for(i in seq_along(n))
195 l[[i]] <- Recall(n[i])
196 return(l)
197 }
198 if(n != round(n) || n < 2)
199 return(n)
200 tab <- 2:n
201 fac <- numeric(0)
202 while(n > 1) {
203 while(n %% tab[1] == 0) {
204 fac <- c(fac, tab[1])
205 n <- n/tab[1]
206 }
207 tab <- tab[tab <= n]
208 omit <- tab[1] * c(1, tab[tab <= n/tab[1]])
209 tab <- tab[ - match(omit, tab, nomatch = 0)]
210 }
211 fac
212 }
213
214
215 ##- From: mona kanaan <[email protected]>
216 ##- Date: Fri, 11 Sep 1998 08:52:59 +0100 (BST)
217 ##- To: "'S-News'" <[email protected]>
218 ##- Subject: [S] Summary: Factors (divisors) of an inreger
219
220 ##- Thanks a lot, for everybody who replied to my query.
221 ##- Here is a summary of what was passed on.
222 ##- The first two codes due to Bill Venables and Bill Dunlap give the Prime
223 ##- divisors of an integer(this is what i was actually looking for), the last
224 ##- code gives all divisors but is not efficient for "large"
225 ##- integers (this is what i was trying to avoid).
226 ##-
227 ##- Thanks again
228 ##- Mona
229
230 ## .... Bill Venables solution [see above !] ........
231
232
233 ##- -----------------------------------------------------------------
234 ##- -----------------------------------------------------------------
235 ##- Bill Dunlap
236 ##-
237 ##- I use the following factors(), which uses the enclosed primes():
238 ##
239 ## MMä: mv'ed all examples to file ... (now ../demo/prime-numbers.R )
240
241 factors <- function(x)
242 {
243 factor1 <- function(y, max.factor, .Primes)
244 {
245 .Primes <- if(missing(.Primes))
246 primes.t(max.factor) else primes.t(max.factor, .Primes)
247 f <- numeric(0)
248 while(y > 1) {
249 ## note: 1 has no factors according to this
250 which <- y %% .Primes == 0
251 if(sum(which) == 0) {
252 f <- c(f, y)
253 break
254 }
255 else f <- c(f, .Primes[which])
256 y <- y/prod(.Primes[which])
257 }
258 val <- sort(f)
259 if(length(val) && any(big <- val > max.factor^2)) {
260 if(sum(big) != 1)
261 stop("internal error: sum(big)!=1")
262 val <- sort(c(val[!big],
263 Recall(val[big], min(ceiling(sqrt(val[big])),
264 max.factor^2), .Primes)))
265 }
266 val
267 }
268 val <- lapply(x, factor1, 43)
269 names(val) <- as.character(x)
270 val
271 }
272
273 ## MM: this version (Bill Dunlap's maybe slightly modified ?) is
274 ## -- *much* slower than primes() above !
275 primes.t <- function(n, .Primes = c(2, 3, 5, 7, 11, 13, 17, 19,
276 23, 29, 31, 37, 41, 43))
277 {
278 ## primes() function using table
279 if(is.unsorted(.Primes)) stop("'.Primes' must be increasing")
280 nP <- length(.Primes <- as.integer(.Primes))
281 maxP <- .Primes[nP]
282 stopifnot(.Primes[1:3] == c(2,3,5),
283 maxP > 30, maxP %% 2 == 1, maxP %% c(3,5) != 0)
284 if(maxP < n) {
285 ## compute longer .Primes by sieve
286 .Primes <- seq(from = 2, to = n)
287 for(i in 1:length(.Primes)) {
288 composite <- .Primes %% .Primes[i] == 0
289 composite[i] <- FALSE
290 if(all(!composite))
291 break
292 .Primes <- .Primes[!composite]
293 if(i >= length(.Primes))
294 break
295 }
296 }
297 .Primes[.Primes <= n]
298 }
299
300
301 ##- factors.simple() is easier to understand and is faster on small numbers
302 ##- but can work very slowly on large numbers with lots of small factors
303 ##- (like numbers arising in combinatorics).
304
305 factors.simple <- function(x)
306 {
307 factor1 <- function(y, .Primes)
308 {
309 f <- numeric(0)
310 while(y > 1) {
311 ## note 1 has no factors according to this
312 which <- y %% .Primes == 0
313 if(sum(which) == 0) {
314 f <- c(f, y)
315 break
316 }
317 else f <- c(f, .Primes[which])
318 y <- y/prod(.Primes[which])
319 }
320 sort(f)
321 }
322 val <- lapply(x, factor1, primes(ceiling(sqrt(max(x)))))
323 names(val) <- as.character(x)
324 val
325 }
326
327 ##----------------------------------------------------------------------------
328 ##----------------------------------------------------------------------------
329 ##----------------------------------------------------------------------------
330 ##
331 ## Guido Schwarzer ,Gardar Johannesson, Remy vande Ven, Henrik Aalborg-Nielsen
332
333 DIV <- function(N) {
334 N.seq <- 1:N
335 N.seq[(N %% N.seq) == 0]
336 }
337
338 ##- From: "Frank E Harrell Jr" <[email protected]>
339 ##- To: "s-news" <[email protected]>
340 ##- Subject: [S] An improved factorize()
341 ##- Date: Sat, 12 Sep 1998 22:34:05 -0400
342 ##-
343 ##- Here is a modification of Michael Bramley's ([email protected]) factorize
344 ##- function with memory usage of approx. the square root of the original.
345
346 divisors <- function(n)
347 {
348 ## Frank E Harrell Jr -- called this "factorize()"
349 p <- n/(z <- 1:ceiling(sqrt(n)))
350 z <- z[trunc(p) == p]
351 unique(c(z, rev(n/z)))
352 }
353
354 ##- From: Paul A Tukey <[email protected]>
355 ##- Date: Wed, 16 Sep 1998 18:27:15 -0400 (EDT)
356 ##- To: [email protected], [email protected], [email protected]
357 ##- Subject: Re: [S] Prime divisors
358
359 ##- This discussion has been fun.
360
361 ##- Seems to me we've been gradually heading toward
362 ##- computing the prime factorization of a number.
363 ##- That is, a collection of prime numbers (with possible
364 ##- duplication) whose product is the given number.
365
366 ##- A recursive layer on top of Frank Harrell's factorize() does
367 ##- it -- but the code below uses a slightly shortened version
368 ##- of factorize() that only returns the smallest divisor > 1.
369
370 fac <- function(n) {
371 p <- n/(z <- 1:floor(sqrt(n)))
372 z <- z[trunc(p) == p]
373 c(z, rev(n/z))[2]
374 }
375
376 pfac <- function(n, nn = 0)
377 {
378 if(nn == 0)
379 pfac(n, fac(n))
380 else if(n <= nn)
381 nn
382 else c(nn, pfac(n/nn))
383 }
384
385 ##- Note that prod(pfac(n)) == n.
386
387 ##- Now I'm sure someone can write a more elegant version.
388 ##- Also, recursion is probably neither memory-efficient
389 ##- nor CPU-efficient in Splus.
390
391 ##- -- Paul Tukey
392 ##- Bellcore
393
394 ##------------------- GCD and LCM ----------------------> ../man/gcd.Rd
395
396 ##' Greatest Common Divisor of 2
397 GCD <- function (a, b) {
398 stopifnot(a == (a <- floor(a)), b == (b <- floor(b)), length(a) == 1L, length(b) == 1L,
399 a > 0L, b > 0L)
400 while (b != 0) {
401 q <- a %/% b
402 R <- a - b * q
403 a <- b
404 b <- R
405 }
406 a
407 }
408
409 ##' Least Common Multiple of _several_ integers
410 LCM <- function(n, ...) { # least common multiple of *several* integer numbers in n,...
411 if(...length()) n <- c(n, as.integer(unlist(list(...))))
412 stopifnot(n == (n <- as.integer(n)))
413 ## LCM(a, b, c, ...) = LCM(...., LCM(LCM(a, b), c), ...); LCM(a,b) = a*b / GCD(a,b)
414 N <- length(n)
415 if(!N) return(1)
416 p <- as.double(n[1L]) # numeric because of "easy" overflow
417 if(N > 1L) for(j in 2L:N)
418 p <- (p * n[j]) %/% GCD(p, n[j])
419 p
420 }