primeFactorizeSieve: Generate Prime Factorization for Numbers in a Range

View source: R/NumberTheory.R

primeFactorizeSieveR Documentation

Generate Prime Factorization for Numbers in a Range


Generates the prime factorization of all numbers between bound1 and bound2 (if supplied) or all numbers up to bound1.


primeFactorizeSieve(bound1, bound2 = NULL, namedList = FALSE, nThreads = NULL)



Positive integer or numeric value.


Positive integer or numeric value.


Logical flag. If TRUE, a named list is returned. The default is FALSE.


Specific number of threads to be used. The default is NULL.


This function is useful when many prime factorizations are needed. Instead of generating the prime factorization on the fly, one can reference the indices/names of the generated list.

This algorithm benefits greatly from the fast integer division library 'libdivide'. The following is from

  • libdivide allows you to replace expensive integer divides with comparatively cheap multiplication and bitshifts. Compilers usually do this, but only when the divisor is known at compile time. libdivide allows you to take advantage of it at runtime. The result is that integer division can become faster - a lot faster.


Returns a named/unnamed list of integer vectors if max(bound1, bound2) < 2^{31}, or a list of numeric vectors otherwise.


The maximum value for either of the bounds is 2^{53} - 1.


Joseph Wood


See Also

primeFactorize, divisorsSieve, factorize


## Generate some random data
mySamp <- sample(10^5, 5*10^4)

## Generate prime factorizations up
## to 10^5 (max element from mySamp)
system.time(allPFacs <- primeFactorizeSieve(10^5))

## Use generated prime factorization for further
## analysis by accessing the index of allPFacs
for (s in mySamp) {
    pFac <- allPFacs[[s]]
    ## Continue algorithm

## Generating prime factorizations over
## a range is efficient as well
system.time(primeFactorizeSieve(10^12, 10^12 + 10^5))

## Set 'namedList' to TRUE to return a named list
primeFactorizeSieve(27, 30, namedList = TRUE)

## Using nThreads
system.time(primeFactorizeSieve(1e4, 5e4, nThreads = 2))

RcppAlgos documentation built on Oct. 3, 2023, 1:07 a.m.