Package {RcppAlgos}


Version: 2.10.4
Title: High Performance Tools for Combinatorics and Computational Mathematics
Description: Provides optimized functions and flexible iterators implemented in C++ for solving problems in combinatorics and computational mathematics. Handles various combinatorial objects including combinations, permutations, integer partitions and compositions, Cartesian products, unordered Cartesian products, and partition of groups. Utilizes the RMatrix class from 'RcppParallel' for thread safety. The combination and permutation functions contain constraint parameters that allow for generation of all results of a vector meeting specific criteria (e.g. finding all combinations such that the sum is between two bounds). Capable of ranking/unranking combinatorial objects efficiently (e.g. retrieve only the nth lexicographical result) which sets up nicely for parallelization as well as random sampling. Gmp support permits exploration where the total number of results is large (e.g. comboSample(10000, 500, n = 4)). Additionally, there are several high performance number theoretic functions that are useful for problems common in computational mathematics. Some of these functions make use of the fast integer division library 'libdivide'. The primeSieve function is based on the segmented sieve of Eratosthenes implementation by Kim Walisch. It is also efficient for large numbers by using the cache friendly improvements originally developed by Tomás Oliveira. Prime counting supports Legendre, Meissel, and Lehmer methods. The Legendre implementation and shared partial-sieve calculation build on the work of Kim Walisch.
URL: https://jwood000.github.io/RcppAlgos/, https://github.com/jwood000/RcppAlgos, https://gmplib.org/, https://github.com/kimwalisch/primesieve, https://libdivide.com, https://github.com/kimwalisch/primecount, https://ridiculousfish.com/, https://sweet.ua.pt/tos/software/prime_sieve.html
BugReports: https://github.com/jwood000/RcppAlgos/issues
LinkingTo: cpp11
Imports: gmp, methods
Suggests: testthat, partitions, microbenchmark, knitr, RcppBigIntAlgos, rmarkdown, prettydoc, covr
Config/Needs/website: pkgdown, xml2
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
SystemRequirements: gmp (>= 4.2.3)
VignetteBuilder: knitr
NeedsCompilation: yes
Encoding: UTF-8
RoxygenNote: 7.2.3
Packaged: 2026-11-20 17:40:53 UTC; owacasa
Author: Joseph Wood [aut, cre], Joseph J. Allaire [ctb] (Original author of RMatrix.h, copied from RcppParallel)
Maintainer: Joseph Wood <jwood000@gmail.com>
Repository: CRAN
Date/Publication: 2026-11-23 15:10:17 UTC

High Performance Tools for Combinatorics and Computational Mathematics

Description

The RcppAlgos package attacks age-old problems in combinatorics and computational mathematics.

Goals

  1. The main goal is to encourage fresh and creative approaches to foundational problems. The question that most appropriately summarizes RcppAlgos is: "Can we do better?".

  2. Provide highly optimized functions that facilitates a broader spectrum of researchable cases. E.g

    • Investigating the structure of large numbers over wide ranges:

      • primeFactorizeSieve(10^13 - 10^7, 10^13 + 10^7)

      • primeSieve(2^53 - 10^10, 2^53 - 1, nThreads = 32)

    • Easily explore combinations/permutations/partitions that would otherwise be inaccessible due to time of execution/memory constraints:

      • c_iter = comboIter(10000, 100)
        bigSamp = gmp::urand.bigz(3, gmp::log2.bigz(comboCount(10000, 100)))
        c_iter[[bigSamp]] ## flexible iterator allows random sampling
      • p_iter = partitionsIter(5000, 100, target = 6000)
        p_iter[[1e9]] ## start iterating from index = 1e9
        p_iter@nextIter()
        p_iter@nextNIter(1e3)
      • comboGeneral(150, 5, constraintFun = "sum", Parallel = TRUE)

      • parallel::mclapply(seq(...), function(x) {
                    temp = permuteGeneral(15, 10, lower = x, upper = y)
                    ## analyze permutations
                    ## output results
            }, mc.cores = detectCores() - 1))
      • partitionsGeneral(0:80, repetition = TRUE)
      • permuteSample(rnorm(100), 10, freqs = rep(1:4, 25), n = 15, seed = 123)

      • set.seed(123)
        comboGeneral(runif(42, 0, 50), 10,
                     constraintFun = "mean",
                     comparisonFun = c(">","<"),
                     limitConstraints = c(39.876, 42.123))
  3. Speed!!!.... You will find that the functions in RcppAlgos are some of the fastest of their type available in R.

Author(s)

Joseph Wood


S4-class for Exposing C++ Cartesian Class

Description

The Cartesian class is an S4-class that exposes C++ classes that provide access to iterators and other useful methods.

Slots

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

randomAccess

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Author(s)

Joseph Wood

See Also

ComboGroups-class, Combo-class, Partitions-class

Examples

  showClass("Cartesian")

S4-classes for Exposing C++ Combinatorial Classes

Description

The Combo class family are S4-classes that expose C++ classes that provide access to iterators and other useful methods.

Slots

of "Combo" and all classes inheriting from it:

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

prevIter

Retrieve the previous lexicographical result (the next reverse lexicographical result)

prevNIter

Pass an integer n to retrieve the previous n lexicographical results (the next n reverse lexicographical results)

prevRemaining

Retrieve all remaining reverse lexicographical results

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

randomAccess

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Author(s)

Joseph Wood

See Also

Partitions-class, Constraints-class

Examples

  showClass("Combo")

S4-class for Exposing C++ ComboGroups Class

Description

The ComboGroups class is an S4-class that exposes C++ classes that provide access to iterators and other useful methods.

Slots

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

randomAccess

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Author(s)

Joseph Wood

See Also

Combo-class, Constraints-class, Partitions-class

Examples

  showClass("ComboGroups")

S4-class for Exposing C++ Constraints Class

Description

The Constraints class is an S4-class that exposes C++ classes that provide access to iterators and other useful methods.

Slots

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

Author(s)

Joseph Wood

See Also

Combo-class, Partitions-class

Examples

  showClass("Constraints")

S4-class for Exposing C++ Partitions Class

Description

The Partitions class is an S4-class that exposes C++ classes that provide access to iterators and other useful methods.

Slots

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

randomAccess

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Author(s)

Joseph Wood

See Also

Combo-class, Constraints-class

Examples

  showClass("Partitions")

Number of combinations/permutations

Description

Calculate the number of combinations/permutations of a vector chosen m at a time with or without replacement. Additionally, these functions can calculate the number of combinations/permutations of multisets.

Usage

comboCount(v, m = NULL, ...)
permuteCount(v, m = NULL, ...)

## Default S3 method:
comboCount(v, m = NULL, repetition = FALSE, freqs = NULL, ...)
## Default S3 method:
permuteCount(v, m = NULL, repetition = FALSE, freqs = NULL, ...)

## S3 method for class 'table'
comboCount(v, m = NULL, ...)
## S3 method for class 'table'
permuteCount(v, m = NULL, ...)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

m

Number of elements to choose. If repetition = TRUE or freqs is utilized, m can exceed the length of v. If m = NULL, the length will default to length(v) or sum(freqs).

...

Further arguments passed to methods.

repetition

Logical value indicating whether combinations/permutations should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all combinations/permutations of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

Value

A numerical value representing the total number of combinations/permutations.

Note

When the number of results exceeds 2^{53} - 1, a number of class bigz is returned.

See Also

comboGeneral, permuteGeneral

Examples

## Same interface as the respective "general" functions:
## i.e. comboGeneral & permuteGeneral

permuteCount(-5)
permuteCount(5)
comboCount(25, 12)
permuteCount(15, 7, TRUE)
comboCount(25, 12, freqs = rep(2, 25))

## Return object of class 'bigz'
comboCount(250, 15, freqs = rep(2, 250))

Generate Combinations and Permutations of a Vector with/without Constraints

Description

Usage

comboGeneral(v, m = NULL, ...)
permuteGeneral(v, m = NULL, ...)

## S3 method for class 'numeric'
comboGeneral(v, m = NULL, repetition = FALSE, freqs = NULL,
             lower = NULL, upper = NULL, constraintFun = NULL,
             comparisonFun = NULL, limitConstraints = NULL,
             keepResults = NULL, FUN = NULL, Parallel = FALSE,
             nThreads = NULL, tolerance = NULL, FUN.VALUE = NULL, ...)

## S3 method for class 'numeric'
permuteGeneral(v, m = NULL, repetition = FALSE, freqs = NULL,
               lower = NULL, upper = NULL, constraintFun = NULL,
               comparisonFun = NULL, limitConstraints = NULL,
               keepResults = NULL, FUN = NULL, Parallel = FALSE,
               nThreads = NULL, tolerance = NULL, FUN.VALUE = NULL, ...)

## S3 method for class 'factor'
comboGeneral(
    v, m = NULL, repetition = FALSE, freqs = NULL, lower = NULL, upper = NULL,
    FUN = NULL, Parallel = FALSE, nThreads = NULL, FUN.VALUE = NULL, ...
)
## S3 method for class 'factor'
permuteGeneral(
    v, m = NULL, repetition = FALSE, freqs = NULL, lower = NULL, upper = NULL,
    FUN = NULL, Parallel = FALSE, nThreads = NULL, FUN.VALUE = NULL, ...
)

## Default S3 method:
comboGeneral(v, m = NULL, repetition = FALSE,
             freqs = NULL, lower = NULL, upper = NULL,
             FUN = NULL, FUN.VALUE = NULL, ...)
## Default S3 method:
permuteGeneral(v, m = NULL, repetition = FALSE,
               freqs = NULL, lower = NULL, upper = NULL,
               FUN = NULL, FUN.VALUE = NULL, ...)

## S3 method for class 'table'
comboGeneral(
    v, m = NULL, lower = NULL, upper = NULL, constraintFun = NULL,
    comparisonFun = NULL, limitConstraints = NULL, keepResults = NULL,
    FUN = NULL, Parallel = FALSE, nThreads = NULL, tolerance = NULL,
    FUN.VALUE = NULL, ...
)
## S3 method for class 'table'
permuteGeneral(
    v, m = NULL, lower = NULL, upper = NULL, constraintFun = NULL,
    comparisonFun = NULL, limitConstraints = NULL, keepResults = NULL,
    FUN = NULL, Parallel = FALSE, nThreads = NULL, tolerance = NULL,
    FUN.VALUE = NULL, ...
)

## S3 method for class 'list'
comboGeneral(v, m = NULL, repetition = FALSE,
             freqs = NULL, lower = NULL, upper = NULL, ...)
## S3 method for class 'list'
permuteGeneral(v, m = NULL, repetition = FALSE,
               freqs = NULL, lower = NULL, upper = NULL, ...)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

m

Number of elements to choose. If repetition = TRUE or freqs is utilized, m can exceed the length of v. If m = NULL, the length will default to length(v) or sum(freqs).

...

Further arguments passed to methods.

repetition

Logical value indicating whether combinations/permutations should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all combinations/permutations of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

lower

The lower bound, using one-based ranks. Without constraints, this is the rank of the first combination/permutation to generate (e.g. comboGeneral(5, 3, lower = 6) is equivalent to comboGeneral(5, 3)[6:choose(5, 3), ]). For constrained permuteGeneral, this always selects ordinary permutation ranks to test, including when lower = 1. It does not select the rank of a matching result. See Ordering and bounds in Details for the distinction from supported partition calls through comboGeneral.

upper

The upper bound. Similar to lower, however this parameter allows the user to stop generation at a specific combination/permutation (e.g. comboGeneral(5, 3, upper = 5) is equivalent to comboGeneral(5, 3)[1:5, ])

For constrained permuteGeneral and generic constrained searches, if lower isn't supplied, upper caps the number of matching results returned. For example, upper = 100 alone returns the first 100 matches, while lower = 1 and upper = 100 test the first 100 candidates.

When comboGeneral uses a supported partition algorithm with constraintFun = "sum" and comparisonFun = "==", including multiset partitions, both bounds index matching partitions in lexicographical order. These calls use the same bounds as partitionsGeneral: supplying lower = 1 or omitting lower returns the same prefix when matches exist. If there are no matches, omitting both bounds returns an empty matrix; explicit positive bounds exceed the zero result count and raise an error.

In addition to the benefits listed for lower, this parameter is useful when the total number of combinations/permutations without constraint is large and you expect/need a small number of combinations/permutations that meet a certain criteria. Using upper can improve run time if used judiciously as we call the member function reserve of std::vector. See examples below.

constraintFun

Function to be applied to the elements of v that should be passed as a string (e.g. constraintFun = "sum"). The possible constraint functions are: "sum", "prod", "mean", "max", & "min". The default is NULL, meaning no function is applied.

comparisonFun

Comparison operator that will be used to compare limitConstraints with the result of constraintFun applied to v. It should be passed as a string or a vector of two strings (e.g. comparisonFun = "<=" or comparisonFun = c(">","<")). The possible comparison operators are: "<", ">", "<=", ">=", "==". The default is NULL.

When comparisonFun is a vector of two comparison strings, e.g comparisonFun = c(comp1, comp2), and limitConstraints is a vector of two numerical values, e.g limitConstraints = c(x1, x2), the combinations/permutations will be filtered in one of the following two ways:

  1. When comp1 is one of the 'greater-than' operators (i.e. ">=" or ">"), comp2 is one of the 'less-than' operators (i.e. "<=" or "<"), and x1 < x2, the combinations/permutations that are returned will have a value (after constraintFun has been applied) between x1 and x2.

  2. When comp1 and comp2 are defined as in #1 and x1 > x2, the combinations/permutations that are returned will have a value outside the range of x1 and x2. See the examples below.

In other words, the first comparison operator is applied to the first limit and the second operator is applied to the second limit.

limitConstraints

This is the value(s) that will be used for comparison. Can be passed as a single value or a vector of two numerical values. The default is NULL. See the definition of comparisonFun as well as the examples below for more information.

keepResults

A logical flag indicating if the result of constraintFun applied to v should be displayed; if TRUE, an additional column of results will be added to the resulting matrix. The default is FALSE. If user is only applying constraintFun, keepResults will default to TRUE.

E.g. The following are equivalent and will produce a 4^{th} column of row sums:

  • comboGeneral(5, 3 constraintFun = "sum", keepResults = TRUE)

  • comboGeneral(5, 3 constraintFun = "sum")

FUN

Function to be applied to each combination/permutation. The default is NULL.

Parallel

Logical value indicating whether combinations/permutations should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

tolerance

A numeric value greater than or equal to zero. This parameter is utilized when a constraint is applied on a numeric vector. The default value is 0 when it can be determined that whole values are being utilized, otherwise it is sqrt(.Machine$double.eps) which is approximately 1.5e-8. N.B. If the input vector is of type integer, this parameter will be ignored and strict equality will be enforced.

FUN.VALUE

A template for the return value from FUN. See 'Details' of vapply for more information.

Details

Ordering and bounds

Without constraints, permuteGeneral generates ordinary permutations in lexicographical order, and lower and upper index that order.

For supported partition cases with constraintFun = "sum" and comparisonFun = "==", omitting lower uses partition-then-permute order: matching partitions are visited in lexicographical order, and all distinct permutations of each partition are emitted in lexicographical order before moving to the next partition. The combined output need not be globally lexicographical. This applies also when an equivalent composition algorithm exists. upper alone caps the number of matching rows and may stop within a permutation block. These partition cases use integer-valued, evenly spaced source vectors and an integer target, including supported mapped and multiset cases; see partitionsGeneral.

For any constrained permuteGeneral call with lower supplied, lower and upper instead specify an inclusive range of ordinary permutation ranks, ignoring the constraint when assigning ranks. Only matching candidates in that range are returned, in lexicographical order. If upper is omitted, testing continues through the remaining candidates. Thus lower = 1 is not redundant: upper = 100 alone caps matches, whereas lower = 1, upper = 100 tests 100 candidates and can return fewer than 100 rows, including none.

compositionsGeneral generates supported compositions in lexicographical order across all matching rows; its bounds index those matching rows. Supported partition calls through comboGeneral also use matching-result ranks. Other constrained calls without lower use their applicable constraint algorithms; their output positions should not be interpreted as composition ranks.

For the general case, finding all combinations/permutations with constraints is optimized by organizing them in such a way that when constraintFun is applied, a partially monotonic sequence is produced. Combinations/permutations are added successively, until a particular combination exceeds the given constraint value for a given constraint/comparison function combo. After this point, we can safely skip several combinations knowing that they will exceed the given constraint value.

There are special cases where more efficient algorithms are dyncamically deployed. These cases center around the subject of integer partitions. See partitionsGeneral for more information.

When there are any negative values in v, constraintFun = "prod", and limitConstraints is provided, producing a monotonic set is non-trivial for the general case. As a result, performance will suffer as all combinations/permutations must be tested against the constraint criteria. Throughout the documentation, this case is referred to as special constraints.

Value

Note

Author(s)

Joseph Wood

References

Examples

## No lower: permute each matching partition before moving to the next.
permuteGeneral(6, 3, repetition = TRUE, constraintFun = "sum",
               comparisonFun = "==", limitConstraints = 6, upper = 4)

## Explicit lower: test ordinary permutation ranks 1 through 4.
## Only (1, 1, 4) matches; upper is not a request for four matches.
permuteGeneral(6, 3, repetition = TRUE, constraintFun = "sum",
               comparisonFun = "==", limitConstraints = 6,
               lower = 1, upper = 4)

## Compositions: return the first four matching rows in lexicographic order.
compositionsGeneral(6, 3, repetition = TRUE, target = 6, upper = 4)

comboGeneral(4, 3)
permuteGeneral(3)

permuteGeneral(factor(letters[1:3]), repetition = TRUE)

## permutations of the multiset :
## c(1,1,1,2,2,3)
permuteGeneral(table(c(1,1,1,2,2,3)))

## Example with list
comboGeneral(
    v = list(
        p1 = matrix(1:10, ncol = 2),
        p2 = data.frame(a = letters, b = 1:26),
        p3 = as.complex(1:10)
    ),
    m = 2
)

#### Examples using "upper" and "lower":
## See specific range of permutations
permuteGeneral(75, 10, freqs = rep(1:3, 25),
               lower = 1e12, upper = 1e12 + 10)

## Researcher only needs 10 7-tuples of mySamp
## such that the sum is greater than 7200.
## Generate some random data
set.seed(1009)
mySamp = rnorm(75, 997, 23)
comboGeneral(mySamp, 7, constraintFun = "sum",
             comparisonFun = ">", limitConstraints = 7200, upper = 10)

## Similarly, you can use "lower" to obtain the last rows.
## Generate the last 10 rows
comboGeneral(mySamp, 7, lower = choose(75, 7) - 9)

## Or if you would like to generate a specific chunk,
## use both "lower" and "upper". E.g. Generate one
## million combinations starting with the 900,000,001
## lexicographic combination.
t1 = comboGeneral(mySamp, 7,
                  lower = 9*10^8 + 1,
                  upper = 9*10^8 + 10^6)

## class of the source vector is preserved
class(comboGeneral(5,3)[1,]) == class(1:5)
class(comboGeneral(c(1,2:5),3)[1,]) == class(c(1,2:5))
class(comboGeneral(factor(month.name),3)[1,]) == class(factor(month.name))

## Using keepResults will add a column of results
comboGeneral(-3, 6, TRUE,
             constraintFun = "sum",
             comparisonFun = "==",
             limitConstraints = -8,
             keepResults = TRUE)

## Using multiple constraints:

## Get combinations such that the product
## is between 3000 and 4000 inclusive
comboGeneral(5, 7, TRUE, constraintFun = "prod",
             comparisonFun = c(">=","<="),
             limitConstraints = c(3000, 4000),
             keepResults = TRUE)

## Or, get the combinations such that the
## product is less than or equal to 10 or
## greater than or equal to 40000
comboGeneral(5, 7, TRUE, constraintFun = "prod",
             comparisonFun = c("<=",">="),
             limitConstraints = c(10, 40000),
             keepResults = TRUE)

#### General subset sum problem
set.seed(516781810)
comboGeneral(runif(100, 0, 42), 5, constraintFun = "mean",
             comparisonFun = "==", limitConstraints = 30,
             tolerance = 0.0000002)


#### Integer Partitions
comboGeneral(0:5, 5, TRUE, constraintFun = "sum",
             comparisonFun = "==", limitConstraints = 5)


## Using FUN
comboGeneral(10000, 5, lower = 20, upper = 22,
             FUN = function(x) {
                 which(cummax(x) %% 2 == 1)
             })

## Not run: 
## Parallel example generating more than 2^31 - 1 combinations.
library(parallel)
numCores = detectCores() - 1

## 10086780 evenly divides choose(35, 15) and is "small enough" to
## generate quickly in chunks.
system.time(mclapply(seq(1, comboCount(35, 15), 10086780), function(x) {
    a = comboGeneral(35, 15, lower = x, upper = x + 10086779)
    ## do something
    x
}, mc.cores = numCores))


## Find 13-tuple combinations of 1:25 such
## that the mean is less than 10
system.time(myComb <- comboGeneral(25, 13, FALSE,
                                   constraintFun = "mean",
                                   comparisonFun = "<",
                                   limitConstraints = 10))

## Alternatively, you must generate all combinations and subsequently
## subset to obtain the combinations that meet the criteria
system.time(myComb2 <- combn(25, 13))
system.time(myCols <- which(colMeans(myComb2) < 10))
system.time(myComb2 <- myComb2[, myCols])

## Any variation is much slower
system.time(myComb2 <- combn(25, 13)[,combn(25, 13, mean) < 10])

## Test equality with myComb above
all.equal(myComb, t(myComb2))

## Fun example... see stackoverflow:
## https://stackoverflow.com/q/22218640/4408538
system.time(permuteGeneral(seq(0L,100L,10L), 8, TRUE,
                           constraintFun = "sum",
                           comparisonFun = "==",
                           limitConstraints = 100))

## These are called weak integer compositions. Below, we call
## compositionsGeneral which gives the same output except it
## in lexicographical order. See 'Note' above
system.time(compositionsGeneral(seq(0L,100L,10L), 8, TRUE, weak = TRUE))

## End(Not run)

Unordered Cartesian Product

Description

Efficient version of expand.grid where order does not matter. This is a combinatorial variant where groups of elements are treated as equivalent regardless of order. For example, given: {1, 2}, {1, 2}, the unordered Cartesian product is {1, 1}, {1, 2}, {2, 2}. It is loosely equivalent to the following:

Usage

    comboGrid(..., repetition = TRUE, return_df = FALSE)

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

repetition

Logical value indicating whether results should be with or without repetition. The default is TRUE.

return_df

Logical flag to force the output to be a data.frame. The default is FALSE.

Value

When all of the input is of the same type, by default comboGrid produce a matrix (a data.frame otherwise). This can be ignored by setting the argument return_df = TRUE.

Author(s)

Joseph Wood

See Also

expandGrid

Examples

## description example
lst = list(1:2, 1:2)

t = expand.grid(lst)
t = t[do.call(order, t), ]
key = apply(t, 1, function(x) paste0(sort(x), collapse = ""))
t[!duplicated(key), ]

## vs using comboGrid. N.B. Output is a matrix
comboGrid(lst)

## Force a data.frame to be returned
comboGrid(lst, return_df = TRUE)

## Input vectors are of different type, so a data.frame is returned
expGridNoOrder = comboGrid(1:5, 3:9, letters[1:5], letters[c(1,4,5,8)])
head(expGridNoOrder)
tail(expGridNoOrder)

expGridNoOrderNoRep = comboGrid(1:5, 3:9, letters[1:5],
                                letters[c(1,4,5,8)], repetition = FALSE)

head(expGridNoOrderNoRep)
tail(expGridNoOrderNoRep)

Partition a Vector into Groups

Description

Usage

comboGroups(v, numGroups = NULL, grpSizes = NULL,
            retType = "matrix", lower = NULL, upper = NULL,
            Parallel = FALSE, nThreads = NULL)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

numGroups

An Integer. The number of groups that the vector will be partitioned into. The default is NULL. If provided and grpSize is NULL, it must divide the length of v (if v is a vector) or v (if v is a scalar).

grpSizes

A vector of whole numbers representing the size of each group. The default is NULL. If provided, the sum of the elements must total the length of v (if v is a vector) or v (if v is a scalar).

retType

A string, "3Darray" or "matrix", that determines the shape of the output. The default is "matrix". Note, "3Darray" can only be used when the size of each group is uniform. When the size of each group varies, the return output will always be a matrix.

lower

The lower bound. Partitions of groups are generated lexicographically, thus utilizing this argument will determine which specific result to start generating from (e.g. comboGroups(8, 2, lower = 30) is equivalent to comboGroups(8, 2)[30:comboGroupsCount(8, 2), ]). This argument along with upper is very useful for generating results in chunks allowing for easy parallelization.

upper

The upper bound. Similar to lower, however this parameter allows the user to stop generation at a specific result (e.g. comboGroups(8, 2, upper = 5) is equivalent to comboGroups(8, 2)[1:5, ])

Parallel

Logical value indicating whether results should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

Details

Conceptually, this problem can be viewed as generating all permutations of the vector v and removing the within group permutations. To illustrate this, let us consider the case of generating partitions of 1:8 into 2 groups each of size 4.

Value

By default, a matrix is returned with column names corresponding to the associated group. If retType = "3Darray", a named 3D array is returned.

Note

Author(s)

Joseph Wood

Examples

## return a matrix
comboGroups(8, 2)

## or a 3 dimensional array
temp = comboGroups(8, 2, retType = "3Darray")

## view the first partition
temp[1, , ]

## Example with groups of varying size
comboGroups(8, grpSizes = c(3, 5))

total = comboGroupsCount(11, grpSizes = c(3, 3, 5))

## Start generating from particular index
comboGroups(11, grpSizes = c(3, 3, 5), lower = total - 20)

Number of Partitions of a Vector into Groups

Description

Calculate the number of partitions of a vector into groups. See the related integer sequences A025035-A025042 at OEIS (E.g. A025036 for Number of partitions of 1, 2, ..., 4n into sets of size 4.)

Usage

comboGroupsCount(v, numGroups = NULL, grpSizes = NULL)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

numGroups

An Integer. The number of groups that the vector will be partitioned into. The default is NULL. If provided and grpSize is NULL, it must divide the length of v (if v is a vector) or v (if v is a scalar).

grpSizes

A vector of whole numbers representing the size of each group. The default is NULL. If provided, the sum of the elements must total the length of v (if v is a vector) or v (if v is a scalar).

Value

A numerical value representing the total number of partitions of groups.

Note

When the number of results exceeds 2^{53} - 1, a number of class bigz is returned.

Author(s)

Joseph Wood

References

OEIS Integer Sequence A025036

Examples

comboGroupsCount(16, 4)
comboGroupsCount(16, grpSizes = c(1:4, 6))
comboGroupsCount(28, grpSizes = rep(2:5, each = 2))

comboGroups Iterator

Description

Usage

comboGroupsIter(v, numGroups = NULL, grpSizes = NULL,
                retType = "matrix", Parallel = FALSE,
                nThreads = NULL)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

numGroups

An Integer. The number of groups that the vector will be partitioned into. The default is NULL. If provided and grpSize is NULL, it must divide the length of v (if v is a vector) or v (if v is a scalar).

grpSizes

A vector of whole numbers representing the size of each group. The default is NULL. If provided, the sum of the elements must total the length of v (if v is a vector) or v (if v is a scalar).

retType

A string, "3Darray" or "matrix", that determines the shape of the output. The default is "matrix". Note, "3Darray" can only be used when the size of each group is uniform. When the size of each group varies, the return output will always be a matrix.

Parallel

Logical value indicating whether results should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

Details

Once you initialize a new iterator, the following methods are available:

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

[[

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Value

Note

Author(s)

Joseph Wood

See Also

comboGroups

Examples

a = comboGroupsIter(12, 3)
a@nextIter()
a@nextNIter(3)
a@front()
all_remaining = a@nextRemaining()
dim(all_remaining)
a@summary()
a@back()
a[[5]]
a@summary()
a[[c(1, 17, 3)]]
a@summary()

Sample Partitions of a Vector into Groups

Description

Usage

comboGroupsSample(v, numGroups = NULL, grpSizes = NULL, retType = "matrix",
                  n = NULL, sampleVec = NULL, seed = NULL, Parallel = FALSE,
                  nThreads = NULL, namedSample = FALSE)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

numGroups

An Integer. The number of groups that the vector will be partitioned into. The default is NULL. If provided and grpSize is NULL, it must divide the length of v (if v is a vector) or v (if v is a scalar).

grpSizes

A vector of whole numbers representing the size of each group. The default is NULL. If provided, the sum of the elements must total the length of v (if v is a vector) or v (if v is a scalar).

retType

A string, "3Darray" or "matrix", that determines the shape of the output. The default is "matrix". Note, "3Darray" can only be used when the size of each group is uniform. When the size of each group varies, the return output will always be a matrix.

n

Number of results to return. The default is NULL.

sampleVec

A vector of numbers representing the lexicographical partition of groups to return. Accepts vectors of class bigz as well as vectors of characters

seed

Random seed initialization. The default is NULL. N.B. If the gmp library is needed, this parameter must be set in order to have reproducible results (E.g set.seed() has no effect in these cases).

Parallel

Logical value indicating whether results should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). This is also capped by the number of results requested (e.g. with 16 available threads and 5 results requested, up to 5 threads may be used, since min(16 - 1, 5) = 5). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

namedSample

Logical flag. If TRUE, rownames corresponding to the lexicographical result, will be added to the returned matrix. The default is FALSE.

Details

These algorithms rely on efficiently generating the n^{th} lexicographical result.

Value

By default, a matrix is returned with column names corresponding to the associated group. If retType = "3Darray", a 3D array is returned.

Author(s)

Joseph Wood

References

Lexicographical order

Examples

## generate 10 random partitions of groups of equal size
comboGroupsSample(10, 2, n = 10, seed = 123)

## generate 10 random partitions of groups of varying sizes
comboGroupsSample(10, grpSizes = 1:4, n = 10, seed = 123)

## using sampleVec to generate specific results
comboGroupsSample(15, 5, sampleVec = c(1, 100, 1e3, 1e6))

all.equal(comboGroupsSample(10, 5,
            sampleVec = 1:comboGroupsCount(10, 5)),
         comboGroups(10, 5))

## Examples with enormous number of total results
num = comboGroupsCount(100, 20)
gmp::log2.bigz(num)
## [1] 325.5498

first = gmp::urand.bigz(n = 1, size = 325, seed = 123)
mySamp = do.call(c, lapply(0:10, function(x) gmp::add.bigz(first, x)))

class(mySamp)
## [1] "bigz"

## using the sampling function
cbgSamp = comboGroupsSample(100, 20, sampleVec = mySamp)

## using the standard function
cbgGeneral = comboGroups(100, 20,
                         lower = first,
                         upper = gmp::add.bigz(first, 10))

identical(cbgSamp, cbgGeneral)
## [1] TRUE

## Not run: 
## Using Parallel
system.time(comboGroupsSample(1000, 20, n = 80, seed = 10, Parallel = TRUE))

## End(Not run)

Combination and Permutation Iterator

Description

Usage

comboIter(v, m = NULL, ...)
permuteIter(v, m = NULL, ...)

## S3 method for class 'numeric'
comboIter(v, m = NULL, repetition = FALSE, freqs = NULL,
          constraintFun = NULL, comparisonFun = NULL,
          limitConstraints = NULL, keepResults = NULL,
          FUN = NULL, Parallel = FALSE, nThreads = NULL,
          tolerance = NULL, FUN.VALUE = NULL, ...)

## S3 method for class 'numeric'
permuteIter(v, m = NULL, repetition = FALSE, freqs = NULL,
            constraintFun = NULL, comparisonFun = NULL,
            limitConstraints = NULL, keepResults = NULL,
            FUN = NULL, Parallel = FALSE, nThreads = NULL,
            tolerance = NULL, FUN.VALUE = NULL, ...)

## S3 method for class 'factor'
comboIter(
    v, m = NULL, repetition = FALSE, freqs = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, FUN.VALUE = NULL, ...
)
## S3 method for class 'factor'
permuteIter(
    v, m = NULL, repetition = FALSE, freqs = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, FUN.VALUE = NULL, ...
)

## Default S3 method:
comboIter(
    v, m = NULL, repetition = FALSE, freqs = NULL,
    FUN = NULL, FUN.VALUE = NULL, ...
)
## Default S3 method:
permuteIter(
    v, m = NULL, repetition = FALSE, freqs = NULL,
    FUN = NULL, FUN.VALUE = NULL, ...
)

## S3 method for class 'table'
comboIter(
    v, m = NULL, constraintFun = NULL, comparisonFun = NULL,
    limitConstraints = NULL, keepResults = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, tolerance = NULL, FUN.VALUE = NULL, ...
)
## S3 method for class 'table'
permuteIter(
    v, m = NULL, constraintFun = NULL, comparisonFun = NULL,
    limitConstraints = NULL, keepResults = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, tolerance = NULL, FUN.VALUE = NULL, ...
)

## S3 method for class 'list'
comboIter(v, m = NULL, repetition = FALSE, freqs = NULL, ...)
## S3 method for class 'list'
permuteIter(v, m = NULL, repetition = FALSE, freqs = NULL, ...)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

m

Number of elements to choose. If repetition = TRUE or freqs is utilized, m can exceed the length of v. If m = NULL, the length will default to length(v) or sum(freqs).

...

Further arguments passed to methods.

repetition

Logical value indicating whether combinations/permutations should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all combinations/permutations of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

constraintFun

Function to be applied to the elements of v that should be passed as a string (e.g. constraintFun = "sum"). The possible constraint functions are: "sum", "prod", "mean", "max", & "min". The default is NULL, meaning no function is applied.

comparisonFun

Comparison operator that will be used to compare limitConstraints with the result of constraintFun applied to v. It should be passed as a string or a vector of two strings (e.g. comparisonFun = "<=" or comparisonFun = c(">","<")). The possible comparison operators are: "<", ">", "<=", ">=", "==". The default is NULL.

When comparisonFun is a vector of two comparison strings, e.g comparisonFun = c(comp1, comp2), and limitConstraints is a vector of two numerical values, e.g limitConstraints = c(x1, x2), the combinations/permutations will be filtered in one of the following two ways:

  1. When comp1 is one of the 'greater-than' operators (i.e. ">=" or ">"), comp2 is one of the 'less-than' operators (i.e. "<=" or "<"), and x1 < x2, the combinations/permutations that are returned will have a value (after constraintFun has been applied) between x1 and x2.

  2. When comp1 and comp2 are defined as in #1 and x1 > x2, the combinations/permutations that are returned will have a value outside the range of x1 and x2. See the examples below.

In other words, the first comparison operator is applied to the first limit and the second operator is applied to the second limit.

limitConstraints

This is the value(s) that will be used for comparison. Can be passed as a single value or a vector of two numerical values. The default is NULL. See the definition of comparisonFun as well as the examples below for more information.

keepResults

A logical flag indicating if the result of constraintFun applied to v should be displayed; if TRUE, an additional column of results will be added to the resulting matrix. The default is FALSE. If user is only applying constraintFun, keepResults will default to TRUE.

FUN

Function to be applied to each combination/permutation. The default is NULL.

Parallel

Logical value indicating whether combinations/permutations should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

tolerance

A numeric value greater than or equal to zero. This parameter is utilized when a constraint is applied on a numeric vector. The default value is 0 when it can be determined that whole values are being utilized, otherwise it is sqrt(.Machine$double.eps) which is approximately 1.5e-8. N.B. If the input vector is of type integer, this parameter will be ignored and strict equality will be enforced.

FUN.VALUE

A template for the return value from FUN. See 'Details' of vapply for more information.

Details

Once you initialize a new iterator, the following methods are available via @ (e.g. a@nextIter()) or $ (e.g. a$nextIter()). The preferred practice is to use @ as it is much more efficient (See examples below). Also note that not all of the methods below are available in all cases. See Combo-class, Constraints-class, and Partitions-class:

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

prevIter

Retrieve the previous lexicographical result (the next reverse lexicographical result)

prevNIter

Pass an integer n to retrieve the previous n lexicographical results (the next n reverse lexicographical results)

prevRemaining

Retrieve all remaining reverse lexicographical results

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

[[

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Value

Note

Author(s)

Joseph Wood

References

See Also

comboGeneral, permuteGeneral

Examples

## Typical usage
a = permuteIter(unique(state.region))
a@nextIter()
a@nextNIter(3)
a@front()
a@nextRemaining()
a@prevIter()
a@prevNIter(15)
a@summary()
a@back()
a@prevRemaining()
a[[5]]
a@summary()
a[[c(1, 17, 3)]]
a@summary()

## See examples for comboGeneral where lower and upper are used
set.seed(1009)
mySamp = sort(rnorm(75, 997, 23))

b = comboIter(mySamp, 7,
              constraintFun = "sum",
              comparisonFun = ">",
              limitConstraints = 7200)
b@nextIter()
b@nextNIter(3)
b@summary()
b@currIter()

## Not run: 
## We don't have random access or previous methods
b@back()
#> Error: no slot of name "back" for this object of class "Constraints"
b@prevIter()
#> Error: no slot of name "prevIter" for this object of class "Constraints"

## End(Not run)

Rank Combinations and Permutations

Description

Usage

comboRank(..., v, repetition = FALSE, freqs = NULL, nThreads = NULL)
permuteRank(..., v, repetition = FALSE, freqs = NULL, nThreads = NULL)

Arguments

...

vectors or matrices to be ranked.

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

repetition

Logical value indicating whether combinations/permutations should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all combinations/permutations of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

These algorithms rely on efficiently ranking the n^{th} lexicographical combination/permutation.

Value

A vector of class integer, numeric, or bigz determined by the total number of combinations/permutations

Note

v must be supplied.

Author(s)

Joseph Wood

References

Lexicographical order ranking/unranking

See Also

comboSample, permuteSample

Examples

mySamp = comboSample(30, 8, TRUE, n = 5, seed = 10, namedSample = TRUE)
myRank = comboRank(mySamp, v = 30, repetition = TRUE)
all.equal(as.integer(rownames(mySamp)), myRank)

Sample Combinations and Permutations

Description

Usage

comboSample(v, m = NULL, ...)
permuteSample(v, m = NULL, ...)

## S3 method for class 'numeric'
comboSample(v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
            sampleVec = NULL, seed = NULL, FUN = NULL, Parallel = FALSE,
            nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...)

## S3 method for class 'numeric'
permuteSample(v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
              sampleVec = NULL, seed = NULL, FUN = NULL, Parallel = FALSE,
              nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...)

## S3 method for class 'factor'
comboSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
    sampleVec = NULL, seed = NULL, FUN = NULL, Parallel = FALSE,
    nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)
## S3 method for class 'factor'
permuteSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
    sampleVec = NULL, seed = NULL, FUN = NULL, Parallel = FALSE,
    nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)

## Default S3 method:
comboSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL, sampleVec = NULL,
    seed = NULL, FUN = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)
## Default S3 method:
permuteSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL, sampleVec = NULL,
    seed = NULL, FUN = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)

## S3 method for class 'table'
comboSample(
    v, m = NULL, n = NULL, sampleVec = NULL, seed = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)
## S3 method for class 'table'
permuteSample(
    v, m = NULL, n = NULL, sampleVec = NULL, seed = NULL, FUN = NULL,
    Parallel = FALSE, nThreads = NULL, namedSample = FALSE, FUN.VALUE = NULL, ...
)

## S3 method for class 'list'
comboSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
    sampleVec = NULL, seed = NULL, namedSample = FALSE, ...
)
## S3 method for class 'list'
permuteSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, n = NULL,
    sampleVec = NULL, seed = NULL, namedSample = FALSE, ...
)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

m

Number of elements to choose. If repetition = TRUE or freqs is utilized, m can exceed the length of v. If m = NULL, the length will default to length(v) or sum(freqs).

...

Further arguments passed to methods.

repetition

Logical value indicating whether combinations/permutations should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all combinations/permutations of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

n

Number of combinations/permutations to return. The default is NULL.

sampleVec

A vector of indices representing the lexicographical combination/permutations to return. Accepts whole numbers as well as vectors of class bigz as well as vectors of characters

seed

Random seed initialization. The default is NULL. N.B. If the gmp library is needed, this parameter must be set in order to have reproducible results (E.g set.seed() has no effect in these cases).

FUN

Function to be applied to each combination/permutation. The default is NULL.

Parallel

Logical value indicating whether combinations/permutations should be generated in parallel. The default is FALSE. If TRUE and nThreads = NULL, up to n - 1 threads are used, where n is the number of threads available on your system (both threads may be used on a two-thread system). This is also capped by the number of results requested (e.g. with 16 available threads and 5 results requested, up to 5 threads may be used, since min(16 - 1, 5) = 5). If nThreads is not NULL, it will be given preference (e.g. with 8 available threads, Parallel = TRUE and nThreads = 4, up to 4 threads may be used). In either case, the actual number of threads depends on the useful work in the calculation; small or simple cases may use fewer threads. If your system is single-threaded, the arguments Parallel and nThreads are ignored.

nThreads

Requested number of threads. The default is NULL for serial execution unless Parallel = TRUE. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. See Parallel.

namedSample

Logical flag. If TRUE, rownames corresponding to the lexicographical combination/permutation, will be added to the returned matrix. The default is FALSE.

FUN.VALUE

A template for the return value from FUN. See 'Details' of vapply for more information.

Details

These algorithms rely on efficiently generating the n^{th} lexicographical combination/permutation. This is the process of unranking.

Value

Note

Author(s)

Joseph Wood

References

Lexicographical order

See Also

comboRank, permuteRank

Examples

## generate 10 random combinations
comboSample(30, 8, TRUE, n = 5, seed = 10)

## Using sampleVec to generate specific permutations
fqs   = c(1,2,2,1,2,2,1,2,1,2,2,1,2,1,1)
s_idx = c(1, 10^2, 10^5, 10^8, 10^11)

permuteSample(15, 10, freqs = fqs, sampleVec = s_idx)

## Same example using 'table' method
permuteSample(table(rep(1:15, times = fqs)), 10, sampleVec = s_idx)

## Generate each result one by one...
## Same, but not as efficient as generating iteratively
all.equal(comboSample(10, 5, sampleVec = 1:comboCount(10, 5)),
          comboGeneral(10, 5))

## Examples with enormous number of total permutations
num = permuteCount(10000, 20)
gmp::log2.bigz(num)

first  = gmp::urand.bigz(n = 1, size = 265, seed = 123)
mySamp = do.call(c, lapply(0:10, function(x) gmp::add.bigz(first, x)))

class(mySamp)

## using permuteSample
pSamp = permuteSample(10000, 20, sampleVec = mySamp)

## using permuteGeneral
pGeneral = permuteGeneral(10000, 20,
                          lower = first,
                          upper = gmp::add.bigz(first, 10))

identical(pSamp, pGeneral)

## Using nThreads
permPar = permuteSample(10000, 50, n = 8, seed = 10, nThreads = 2)

## Using FUN
permuteSample(10000, 50, n = 4, seed = 10, FUN = sd)

## Not run: 
## Using Parallel
permuteSample(10000, 50, n = 80, seed = 10, Parallel = TRUE)

## End(Not run)

Vectorized Factorization (Complete)

Description

Function for generating the complete factorization for a vector of numbers.

Usage

divisorsRcpp(v, namedList = FALSE, nThreads = NULL)

Arguments

v

Vector of integers or numeric values. Non-integral values will be coerced to whole numbers.

namedList

Logical flag. If TRUE and the length(v) > 1, a named list is returned. The default is FALSE.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

Efficient algorithm that builds on primeFactorize to generate the complete factorization of many numbers.

Value

Note

The maximum value for each element in v is 2^{53} - 1.

Author(s)

Joseph Wood

References

See Also

primeFactorize

Examples

## Get the complete factorization of a single number
divisorsRcpp(10^8)

## Or get the complete factorization of many numbers
set.seed(29)
myVec <- sample(-1000000:1000000, 1000)
system.time(myFacs <- divisorsRcpp(myVec))

## Return named list
myFacsWithNames <- divisorsRcpp(myVec, namedList = TRUE)

## Using nThreads
system.time(divisorsRcpp(myVec, nThreads = 2))

Generate Complete Factorization for Numbers in a Range

Description

Sieve that generates the complete factorization of all numbers between bound1 and bound2 (if supplied) or all numbers up to bound1.

Usage

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

Arguments

bound1

Positive integer or numeric value.

bound2

Positive integer or numeric value.

namedList

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

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

This function is useful when many complete factorizations are needed. Instead of generating the complete 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 https://libdivide.com/:

Value

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

Note

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

Author(s)

Joseph Wood

References

See Also

divisorsRcpp, primeFactorizeSieve

Examples

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

## Generate complete factorizations up
## to 10^5 (max element from mySamp)
system.time(allFacs <- divisorsSieve(10^5))

## Use generated complete factorization for further
## analysis by accessing the index of allFacs
for (s in mySamp) {
    myFac <- allFacs[[s]]
    ## Continue algorithm
}

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

## Use nThreads for improved efficiency
system.time(divisorsSieve(10^12, 10^12 + 10^5, nThreads = 2))

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

## Using nThreads
system.time(divisorsSieve(1e5, 2e5, nThreads = 2))

Apply Euler's Phi Function to Every Element in a Range

Description

Sieve that generates the number of coprime elements for every number between bound1 and bound2 (if supplied) or all numbers up to bound1. This is equivalent to applying Euler's phi function (often written as \phi(x)) to every number in a given range.

Usage

eulerPhiSieve(bound1, bound2 = NULL, namedVector = FALSE, nThreads = NULL)

Arguments

bound1

Positive integer or numeric value.

bound2

Positive integer or numeric value.

namedVector

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

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

For the simple case (i.e. when bound2 = NULL), this algorithm first generates all primes up to n via the sieve of Eratosthenes. We use these primes to sieve over the sequence 1:n, dividing each value by p, creating a temporary value that will be subtracted from the original value at each index (i.e. equivalent to multiply each index by (1 - 1/p) but more efficient as we don't have to deal with floating point numbers). The case when is.null(bound2) = FALSE is more complicated but the basic ideas still hold.

This function is very useful when you need to calculate Euler's phi function for many numbers in a range as performing this calculation on the fly can be computationally expensive.

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

Value

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

Note

The maximum allowed value is 2^{53} - 1.

Author(s)

Joseph Wood

References

See Also

primePhi for the different partial-sieve function \Phi(n, a) used in prime counting.

Examples

## Generate some random data
set.seed(496)
mySamp <- sample(10^6, 5*10^5)

## Generate number of coprime elements for many numbers
system.time(myPhis <- eulerPhiSieve(10^6))

## Now use result in algorithm
for (s in mySamp) {
    sPhi <- myPhis[s]
    ## Continue algorithm
}

## See https://projecteuler.net
system.time(which.max((1:10^6)/eulerPhiSieve(10^6)))

## Generating number of coprime elements
## for every number in a range is no problem
system.time(myPhiRange <- eulerPhiSieve(10^13, 10^13 + 10^6))

## Returning a named vector
eulerPhiSieve(10, 20, namedVector = TRUE)
eulerPhiSieve(10, namedVector = TRUE)

## Using nThreads
system.time(eulerPhiSieve(1e5, 2e5, nThreads = 2))

Cartesian Product

Description

Generate the Cartesian Product of the input vectors. It is very similar to expand.grid however there are some notable differences:

Usage

    expandGrid(..., lower = NULL, upper = NULL,
               nThreads = NULL, return_df = FALSE)

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

lower

The lower bound. Cartesian products are generated lexicographically, thus utilizing this argument will determine which specific product to start generating from (e.g. expandGrid(1:5, 3:11, lower = 6) is equivalent to expandGrid(1:5, 3:11)[6:expandGridCount(1:5, 3:11), ]). This argument along with upper is very useful for generating products in chunks allowing for easy parallelization.

upper

The upper bound. Similar to lower, however this parameter allows the user to stop generation at a specific product (e.g. expandGrid(1:5, 3:11, upper = 5) is equivalent to expandGrid(1:5, 3:11)[1:5, ])

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

return_df

Logical flag to force the output to be a data.frame. The default is FALSE.

Value

When all of the input is of the same type, by default expandGrid produces a matrix (a data.frame otherwise). This can be ignored by setting the argument return_df = TRUE.

Author(s)

Joseph Wood

See Also

comboGrid

Examples

## description example
lst = list(1:2, 1:2)

## Using base R
t = expand.grid(lst)

## vs using expandGrid. N.B. Output is a matrix
expandGrid(lst)

## Force a data.frame to be returned
expandGrid(lst, return_df = TRUE)

lst = Map(function(x, y) x:y, 8:14, 15:21)

## Use multiple threads for greater efficiency
system.time(expandGrid(lst, nThreads = 2))

Count of the Cartesian Product

Description

Calculate the number of Cartesian products of the input vectors.

Usage

    expandGridCount(...)

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

Value

When the number of results exceeds 2^{53} - 1, a number of class bigz is returned.

Author(s)

Joseph Wood

See Also

expandGrid

Examples

## description example
lst = list(1:2, 1:2)

## Using base R
t = expand.grid(lst)
nrow(t)

## vs calling expandGridCount directly
expandGridCount(lst)

## Call it just like you would if you were generating the results
expandGridCount(1:5, 3:9, letters[1:5], letters[c(1,4,5,8)])

## Same as
nrow(expand.grid(1:5, 3:9, letters[1:5], letters[c(1,4,5,8)]))

lst = Map(function(x, y) x:y, 8:33, 15:40)

## Return object of class 'bigz'
expandGridCount(lst)

expandGrid Iterator

Description

Usage

expandGridIter(..., nThreads = NULL, return_df = FALSE)

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

return_df

Logical flag to force the output to be a data.frame. The default is FALSE.

Details

Once you initialize a new iterator, the following methods are available:

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source input

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

[[

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Value

Note

Author(s)

Joseph Wood

See Also

expandGrid

Examples

a = expandGridIter(factor(state.abb), euro, islands)
a@nextIter()
a@nextNIter(3)
a@front()
all_remaining = a@nextRemaining()
dim(all_remaining)
a@summary()
a@back()
a[[5]]
a@summary()
a[[c(1, 17, 3)]]
a@summary()

Sample the Cartesian Product

Description

Usage

expandGridSample(
    ..., n = NULL, sampleVec = NULL, seed = NULL,
    nThreads = NULL, namedSample = FALSE, return_df = FALSE
)

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

n

Number of results to return. The default is NULL.

sampleVec

A vector of numbers representing the lexicographical partition of groups to return. Accepts vectors of class bigz as well as vectors of characters

seed

Random seed initialization. The default is NULL. N.B. If the gmp library is needed, this parameter must be set in order to have reproducible results (E.g set.seed() has no effect in these cases).

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

namedSample

Logical flag. If TRUE, rownames corresponding to the lexicographical result, will be added to the returned matrix. The default is FALSE.

return_df

Logical flag to force the output to be a data.frame. The default is FALSE.

Details

These algorithms rely on efficiently generating the n^{th} lexicographical result.

Value

When all of the input is of the same type, by default expandGridSample produces a matrix (a data.frame otherwise). This can be ignored by setting the argument return_df = TRUE.

Author(s)

Joseph Wood

References

Lexicographical order

Examples

## input vectors
lst = list(factor(state.abb), euro, islands)

## generate 10 random products
expandGridSample(lst, n = 10, seed = 123)

## using sampleVec to generate specific results
expandGridSample(lst, sampleVec = c(1, 100, 1e3))

all.equal(expandGridSample(lst, sampleVec = 1:expandGridCount(lst)),
         expandGrid(lst))

## Examples with enormous number of total results
big_lst = Map(function(x, y) x:y, 8:33, 15:40)
num = expandGridCount(big_lst)
gmp::log2.bigz(num)
## [1] 78

first = gmp::urand.bigz(n = 1, size = 78, seed = 123)
mySamp = do.call(c, lapply(0:10, function(x) gmp::add.bigz(first, x)))

class(mySamp)
## [1] "bigz"

## using the sampling function
cartSamp = expandGridSample(big_lst, sampleVec = mySamp)

## using the standard function
cartGeneral = expandGrid(big_lst,
                         lower = first,
                         upper = gmp::add.bigz(first, 10))

identical(cartSamp, cartGeneral)
## [1] TRUE

Vectorized Primality Test

Description

Implementation of the Miller-Rabin primality test. Based on the "mp_prime_p" function from the "factorize.c" source file found in the gmp library: https://gmplib.org.

Usage

isPrimeRcpp(v, namedVector = FALSE, nThreads = NULL)

Arguments

v

Vector of integers or numeric values.

namedVector

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

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

The Miller-Rabin primality test is a probabilistic algorithm that makes heavy use of modular exponentiation. At the heart of modular exponentiation is the ability to accurately obtain the remainder of the product of two numbers \pmod p.

With the gmp library, producing accurate calculations for problems like this is trivial because of the nature of the multiple precision data type. However, standard C++ does not afford this luxury and simply relying on a strict translation would have limited this algorithm to numbers less than \sqrt 2^{63} - 1 (N.B. We are taking advantage of the signed 64-bit fixed width integer from the stdint library in C++. If we were confined to base R, the limit would have been \sqrt 2^{53} - 1). RcppAlgos::isPrimeRcpp gets around this limitation with a divide and conquer approach taking advantage of properties of arithmetic.

The problem we are trying to solve can be summarized as follows:

(x_1 * x_2) \pmod p

Now, we rewrite x_2 as x_2 = y_1 + y_2 + \dots + y_n, so that we obtain:

(x_1 * y_1) \pmod p + (x_1 * y_2) \pmod p + \dots + (x_1 * y_n) \pmod p

Where each product (x_1 * y_j) for j <= n is smaller than the original x_1 * x_2. With this approach, we are now capable of handling much larger numbers. Many details have been omitted for clarity.

For a more in depth examination of this topic see Accurate Modular Arithmetic with Double Precision.

Value

Returns a named/unnamed logical vector. If an index is TRUE, the number at that index is prime, otherwise the number is composite.

Note

The maximum value for each element in v is 2^{53} - 1.

References

See Also

primeFactorize, isprime

Examples

## check the primality of a single number
isPrimeRcpp(100)

## check the primality of every number in a vector
isPrimeRcpp(1:100)

set.seed(42)
mySamp <- sample(10^13, 10)

## return named vector for easy identification
isPrimeRcpp(mySamp, namedVector = TRUE)

## Using nThreads
system.time(isPrimeRcpp(mySamp, nThreads = 2))

Find the nth Prime Number

Description

Find the prime number at a given position in the increasing sequence of primes. Positions start at 1, so the first prime is 2.

Usage

nthPrime(n, nThreads = NULL)

Arguments

n

A single positive whole number, at most 252,252,704,148,404. This is the position of the prime to find, not an upper bound on the prime's value.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. This argument is validated even when the result is immediate.

Details

Let p_n denote the nth prime. The result is the unique integer p_n satisfying

\pi(p_n - 1) = n - 1, \qquad \pi(p_n) = n,

where \pi(x) counts the primes less than or equal to x. For example, nthPrime(25) returns 97, whereas primeCount(25) returns 9.

Small positions use a lookup table. Otherwise, the calculation starts with an approximation to p_n, obtains an exact prime count at that location, and finishes with a segmented sieve. At most one additional whole-range prime count is used. Counts over nearby intervals may then refine the search location without recounting all preceding primes. Approximation errors affect the amount of work, not the correctness of the result: the sieve continues until it finds the required prime.

The whole-range counts use Legendre, Meissel, or Lehmer, with the same size and thread thresholds used to choose among those methods in primeCount. Prepared prime and prime-count tables are reused for these counts, then released before interval sieving. Simple size bands, based on the search location rather than the requested position, determine when to switch to sieving. Interval counting and final selection reuse the same sieve as primeSieve. Requested threads apply to both counting and sieving, subject to the useful work available.

The largest supported position is \pi(2^{53} - 1), so the returned prime is at most 2^{53} - 1 and is represented exactly. The table memory grows with the square root of the search location. Near the upper limit, the dense prime-count table alone occupies about 362 MiB, in addition to the prime vector, shared Phi cache, and worker storage. Final selection retains generated primes from a window of at most one million integer positions at a time. Interval counting retains no generated prime values; both sieve stages also require base-prime and worker storage.

Logical inputs TRUE are converted to 1. Missing values, FALSE, non-finite values, fractional values, and vectors of length other than 1 are not supported. nThreads = NULL is supported as described above.

Value

A single prime number. The result is of type integer when it is at most .Machine$integer.max, and numeric otherwise.

References

Axler, C. (2018). New estimates for the nth prime number. https://arxiv.org/abs/1706.03651

Walisch, K. primecount: prime counting and nth-prime algorithms. https://github.com/kimwalisch/primecount

See Also

primeCount, primeSieve, isPrimeRcpp

Examples

nthPrime(1)
nthPrime(25)
nthPrime(1000000)

## The result has exactly n primes at or below it
n <- 1000
p <- nthPrime(n)
primeCount(p)
primeCount(p - 1)

## Use multiple threads for counting and sieving when useful
nthPrime(1000000, nThreads = 2)

Apply Divisor Function to Every Element in a Range

Description

Sieve that generates the number of divisors for every number between bound1 and bound2 (if supplied) or all numbers up to bound1. This is equivalent to applying the divisor function (often written as \sigma(x)) to every number in a given range.

Usage

numDivisorSieve(bound1, bound2 = NULL, namedVector = FALSE, nThreads = NULL)

Arguments

bound1

Positive integer or numeric value.

bound2

Positive integer or numeric value.

namedVector

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

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

Simple and efficient sieve that calculates the number of divisors for every number in a given range. This function is very useful when you need to calculate the number of divisors for many numbers.

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

Value

Returns a named/unnamed integer vector

Note

The maximum allowed value is 2^{53} - 1.

Author(s)

Joseph Wood

References

Examples

## Generate some random data
set.seed(8128)
mySamp <- sample(10^6, 5*10^5)

## Generate number of divisors for
## every number less than a million
system.time(mySigmas <- numDivisorSieve(10^6))

## Now use result in algorithm
for (s in mySamp) {
    sSig <- mySigmas[s]
    ## Continue algorithm
}

## Generating number of divisors for every
## number in a range is no problem
system.time(sigmaRange <- numDivisorSieve(10^13, 10^13 + 10^6))

## Returning a named vector
numDivisorSieve(10, 20, namedVector = TRUE)
numDivisorSieve(10, namedVector = TRUE)

## Using nThreads
system.time(numDivisorSieve(1e5, 2e5, nThreads = 2))

Number of Partitions/Compositions

Description

Calculate the number of partitions/compositions of a vector chosen m at a time with or without replacement. These functions also count supported partitions and compositions of multisets, including weak compositions and non-weak compositions with zero padding.

Usage

partitionsCount(v, m = NULL, ...)
compositionsCount(v, m = NULL, ...)

## Default S3 method:
partitionsCount(v, m = NULL, repetition = FALSE,
                freqs = NULL, target = NULL, ...)
## Default S3 method:
compositionsCount(v, m = NULL, repetition = FALSE,
                  freqs = NULL, target = NULL, weak = FALSE, ...)

## S3 method for class 'table'
partitionsCount(v, m = NULL, target = NULL, ...)
## S3 method for class 'table'
compositionsCount(v, m = NULL, target = NULL, weak = FALSE, ...)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. Only integer and numeric vectors are accepted.

m

Width of the partition. If m = NULL, the length will be determined by the partitioning case (e.g. When we are generating distinct partitions of n, the width will be equal to the smallest m such that sum(1:m) >= n).

...

Further arguments passed to methods.

repetition

Logical value indicating whether partitions/compositions should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all partitions of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

target

Number to be partitioned. If NULL, max(v) will be used.

weak

(Compositions only) Logical flag indicating whether to allow terms of the sequence to be zero.

Value

A numerical value representing the total number of partitions/compositions.

Note

When the number of results exceeds 2^{53} - 1, a number of class bigz is returned.

Counting a general multiset composition does not imply support for generating, iterating, sampling, or ranking those compositions.

See Also

partitionsGeneral, compositionsGeneral

Examples

## Same interface as partitionsGeneral
partitionsCount(25, 5)
compositionsCount(25, 5, TRUE)
partitionsCount(15, 7, TRUE)
partitionsCount(25, 5, freqs = rep(2, 25))

## Count multiset compositions
compositionsCount(1:3, 3, freqs = rep(2, 3), target = 6)
## [1] 6

## Return object of class 'bigz'
partitionsCount(2500, 15, TRUE)
compositionsCount(2500, 15, TRUE)

Generate Partitions/Compositions

Description

The algorithms in RcppAlgos go beyond the traditional integer partition algorithms and can tackle a wide variety of cases.

Usage

partitionsGeneral(v, m = NULL, ...)
compositionsGeneral(v, m = NULL, ...)

## Default S3 method:
partitionsGeneral(
    v, m = NULL, repetition = FALSE, freqs = NULL, target = NULL,
    lower = NULL, upper = NULL, nThreads = NULL, tolerance = NULL, ...
)
## Default S3 method:
compositionsGeneral(
    v, m = NULL, repetition = FALSE, freqs = NULL, target = NULL, weak = FALSE,
    lower = NULL, upper = NULL, nThreads = NULL, tolerance = NULL, ...
)

## S3 method for class 'table'
partitionsGeneral(
    v, m = NULL, target = NULL, lower = NULL,
    upper = NULL, nThreads = NULL, tolerance = NULL, ...
)
## S3 method for class 'table'
compositionsGeneral(
    v, m = NULL, target = NULL, weak = FALSE, lower = NULL,
    upper = NULL, nThreads = NULL, tolerance = NULL, ...
)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. Only integer and numeric vectors are accepted.

m

Width of the partition. If m = NULL, the length will be determined by the partitioning case (e.g. When we are generating distinct partitions of n, the width will be equal to the smallest m such that sum(1:m) >= n).

...

Further arguments passed to methods.

repetition

Logical value indicating whether partitions/compositions should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all partitions of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

lower

The lower bound. Partitions/compositions are generated lexicographically, thus utilizing this argument will determine which specific partition to start generating from (e.g. partitionsGeneral(15, 3, lower = 6) is equivalent to partitionsGeneral(15, 3)[6:partitionsCount(15, 3), ]). This argument along with upper is very useful for generating partitions/compositions in chunks allowing for easy parallelization.

upper

The upper bound. Similar to lower, however this parameter allows the user to stop generation at a specific partition (e.g. partitionsGeneral(15, 3, upper = 5) is equivalent to partitionsGeneral(15, 3)[1:5, ])

target

Number to be partitioned. If NULL, max(v) will be used.

weak

(Compositions only) Logical flag indicating whether to allow terms of the sequence to be zero.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

tolerance

A numeric value greater than or equal to zero. This parameter is utilized when a constraint is applied on a numeric vector. The default value is 0 when it can be determined that whole values are being utilized, otherwise it is sqrt(.Machine$double.eps) which is approximately 1.5e-8. N.B. If the input vector is of type integer, this parameter will be ignored and strict equality will be enforced.

Details

compositionsGeneral generates supported compositions in lexicographical order across all matching rows. Its lower and upper bounds index those matching rows, so lower = 1 returns the same prefix as omitting lower when matching rows exist. For supported partitions and compositions with no matches, omitting both bounds returns an empty matrix. Explicit positive bounds, including lower = 1, exceed the zero result count and raise an error.

This differs from sum/equality calls to permuteGeneral. Without lower, supported constrained permutation calls generate matching partitions and then all distinct permutations of each partition; upper caps matching rows in that order. With lower supplied, permutation bounds select ordinary candidate ranks to filter instead. See Ordering and bounds in comboGeneral.

When zero is present, permuteGeneral treats it as an actual element that can occupy any position, subject to multiplicities. It does not use the zero-padding convention of non-weak compositions.

Value

A matrix is returned with each row containing a vector of length m.

Note

Author(s)

Joseph Wood

References

Examples

partitionsGeneral(1)
partitionsGeneral(-1:0, 1)
partitionsGeneral(-1:0, 1, target = -1)
partitionsGeneral(20, 5)
partitionsGeneral(20, 5, repetition = TRUE)
partitionsGeneral(20, 5, freqs = rep(1:4, 5))
partitionsGeneral(20, 5, TRUE, target = 80)
partitionsGeneral(0:10, repetition = TRUE)
partitionsGeneral(seq(2L, 500L, 23L), 5, target = 1804)

compositionsGeneral(0:10, 5, repetition = TRUE)

set.seed(111)
partitionsGeneral(sample(1000, 20), 5, TRUE, target = 2500)

system.time(one_thread  <- partitionsGeneral(80, 10, TRUE))
system.time(two_threads <- partitionsGeneral(80, 10, TRUE, nThreads = 2))
identical(one_thread, two_threads)

Partition/Composition Iterator

Description

Usage

partitionsIter(v, m = NULL, ...)
compositionsIter(v, m = NULL, ...)

## Default S3 method:
partitionsIter(v, m = NULL, repetition = FALSE,
               freqs = NULL, target = NULL,
               nThreads = NULL, tolerance = NULL, ...)

## Default S3 method:
compositionsIter(v, m = NULL, repetition = FALSE, freqs = NULL,
                 target = NULL, weak = FALSE, nThreads = NULL,
                 tolerance = NULL, ...)

## S3 method for class 'table'
partitionsIter(
    v, m = NULL, target = NULL, nThreads = NULL, tolerance = NULL, ...
)
## S3 method for class 'table'
compositionsIter(
    v, m = NULL, target = NULL, weak = FALSE, nThreads = NULL, tolerance = NULL, ...
)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. Only integer and numeric vectors are accepted.

m

Width of the partition. If m = NULL, the length will be determined by the partitioning case (e.g. When we are generating distinct partitions of n, the width will be equal to the smallest m such that sum(1:m) >= n).

...

Further arguments passed to methods.

repetition

Logical value indicating whether partitions/compositions should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all partitions of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

target

Number to be partitioned. If NULL, max(v) will be used.

weak

(Compositions only) Logical flag indicating whether to allow terms of the sequence to be zero.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

tolerance

A numeric value greater than or equal to zero. This parameter is utilized when a constraint is applied on a numeric vector. The default value is 0 when it can be determined that whole values are being utilized, otherwise it is sqrt(.Machine$double.eps) which is approximately 1.5e-8. N.B. If the input vector is of type integer, this parameter will be ignored and strict equality will be enforced.

Details

Once you initialize a new iterator, the following methods are available:

nextIter

Retrieve the next lexicographical result

nextNIter

Pass an integer n to retrieve the next n lexicographical results

nextRemaining

Retrieve all remaining lexicographical results

currIter

Returns the current iteration

startOver

Resets the iterator

sourceVector

View the source vector

summary

Returns a list of summary information about the iterator

front

Retrieve the first lexicographical result

back

Retrieve the last lexicographical result

[[

Random access method. Pass a single value or a vector of valid indices. If a single value is passed, the internal index of the iterator will be updated, however if a vector is passed the internal state will not change. GMP support allows for flexible indexing.

Value

Note

Author(s)

Joseph Wood

References

See Also

partitionsGeneral, compositionsGeneral

Examples

a = partitionsIter(0:10, repetition = TRUE)
a@nextIter()
a@nextNIter(3)
a@front()
a@nextRemaining()
a@summary()
a@back()
a[[5]]
a@summary()
a[[c(1, 17, 3)]]
a@summary()

## Multiset partitions with random access
b = partitionsIter(40, 5, freqs = rep(1:4, 10), target = 80)
b@nextIter()
b@nextNIter(10)
b@summary()
b@nextIter()
b@currIter()
b[[c(1, 5, 10)]]

Rank Partitions/Compositions

Description

Usage

partitionsRank(..., v, repetition = FALSE, freqs = NULL,
               target = NULL, nThreads = NULL)

compositionsRank(..., v, repetition = FALSE, freqs = NULL,
                 target = NULL, weak = FALSE, nThreads = NULL)

Arguments

...

vectors or matrices to be ranked.

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. All atomic types are supported (See is.atomic).

repetition

Logical value indicating whether partitions/compositions should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all partitions of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

target

Number to be partitioned. If NULL, max(v) will be used.

weak

(Compositions only) Logical flag indicating whether to allow terms of the sequence to be zero.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

These algorithms rely on efficiently ranking the n^{th} lexicographical partition. Supported multiset partitions can be ranked using freqs, including cases with GMP-sized ranks. General multiset compositions can be counted with compositionsCount, but are not supported by compositionsRank.

Value

A vector of class integer, numeric, or bigz determined by the total number of partitions/compositions

Note

v must be supplied.

Author(s)

Joseph Wood

References

Lexicographical order ranking/unranking

See Also

partitionsSample, compositionsSample

Examples

mySamp = partitionsSample(30, 8, TRUE, n = 5, seed = 10, namedSample = TRUE)
myRank = partitionsRank(mySamp, v = 30, repetition = TRUE)
all.equal(as.integer(rownames(mySamp)), myRank)

## Recover the ranks of sampled multiset partitions
indices <- c(1L, 4L)
parts <- partitionsSample(1:5, 3, freqs = rep(2, 5), target = 9,
                          sampleVec = indices)
identical(partitionsRank(parts, v = 1:5, freqs = rep(2, 5), target = 9),
          indices)

Sample Partitions/Compositions

Description

Usage

partitionsSample(v, m = NULL, ...)
compositionsSample(v, m = NULL, ...)

## Default S3 method:
partitionsSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, target = NULL,
    n = NULL, sampleVec = NULL, seed = NULL,
    nThreads = NULL, namedSample = FALSE, ...
)
## Default S3 method:
compositionsSample(
    v, m = NULL, repetition = FALSE, freqs = NULL, target = NULL,
    weak = FALSE, n = NULL, sampleVec = NULL, seed = NULL,
    nThreads = NULL, namedSample = FALSE, ...
)

## S3 method for class 'table'
partitionsSample(
    v, m = NULL, target = NULL, n = NULL,
    sampleVec = NULL, seed = NULL, nThreads = NULL, namedSample = FALSE, ...
)
## S3 method for class 'table'
compositionsSample(
    v, m = NULL, target = NULL, weak = FALSE, n = NULL,
    sampleVec = NULL, seed = NULL, nThreads = NULL, namedSample = FALSE, ...
)

Arguments

v

Source vector. If v is a positive integer, it will be converted to the sequence 1:v. If v is a negative integer, it will be converted to the sequence v:-1. Only integer and numeric vectors are accepted.

m

Width of the partition. If m = NULL, the length will be determined by the partitioning case (e.g. When we are generating distinct partitions of n, the width will be equal to the smallest m such that sum(1:m) >= n).

...

Further arguments passed to methods.

repetition

Logical value indicating whether partitions/compositions should be with or without repetition. The default is FALSE.

freqs

A vector of frequencies used for producing all partitions of a multiset of v. Each element of freqs represents how many times each element of the source vector, v, is repeated. It is analogous to the times argument in rep. The default value is NULL.

target

Number to be partitioned. If NULL, max(v) will be used.

weak

(Compositions only) Logical flag indicating whether to allow terms of the sequence to be zero.

n

Number of partitions/compositions to return. The default is NULL.

sampleVec

A vector of numbers representing the lexicographical partitions/compositions to return. Accepts vectors of class bigz as well as vectors of characters

seed

Random seed initialization. The default is NULL. N.B. If the gmp library is needed, this parameter must be set in order to have reproducible results (E.g set.seed() has no effect in these cases).

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

namedSample

Logical flag. If TRUE, rownames corresponding to the lexicographical partition, will be added to the returned matrix. The default is FALSE.

Details

These algorithms rely on efficiently generating the n^{th} lexicographical partition. This is the process of unranking.

Value

A matrix is returned with each row containing a vector of length m.

Note

Author(s)

Joseph Wood

References

Examples

partitionsSample(100, 10, n = 5)
partitionsSample(100, 10, seed = 42, n = 5, target = 200)

## retrieve specific results (lexicographically)
partitionsCount(100, 10, TRUE, target = 500)
## [1] 175591757896
partitionsSample(100, 10, TRUE, target = 500,
                 sampleVec = c(1, 1000, 175591757896))

## Retrieve specific multiset partitions
partitionsSample(1:5, 3, freqs = rep(2, 5), target = 9,
                 sampleVec = c(1, 4))

Prime Counting Function \pi(x)

Description

Count the prime numbers less than or equal to n, using automatic selection or an explicitly selected Legendre, Meissel, or Lehmer method.

Usage

primeCount(n, nThreads = NULL, method = "auto")

Arguments

n

A single positive whole number, at most 2^{53} - 1.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. For n < 100000, this argument is ignored and execution is serial.

method

One of "auto", "legendre", "meissel", or "lehmer". Matching is case-sensitive and accepts unique abbreviations, as in match.arg. NULL selects "auto".

Details

Method selection

The current "auto" policy selects a method using n and the usable thread budget, which is the requested number of threads capped by the available hardware:

These choices are based on first-call and warmed-call benchmarks. They do not depend on the current cache contents, and they do not guarantee the fastest method for every input or machine. The policy may change with further benchmarking. In particular, a method that improves repeated calls can have a slower first call.

An explicit method uses the named algorithm for every accepted n, including small inputs. The method argument follows nThreads, so existing positional calls such as primeCount(n, 2) retain their meaning. All methods use serial execution when nThreads = NULL.

Counting formulas

Let p_a be the ath prime, and let \Phi(n, a) count the positive integers at most n that are not divisible by any of the first a primes. Its recurrence is

\Phi(n, a) = \Phi(n, a - 1) - \Phi(\lfloor n / p_a \rfloor, a - 1)

with \Phi(n, 0) = n.

For k = 2 or 3, let P_k(n, a) count integers at most n with exactly k prime factors, none among the first a primes. Factors are counted with multiplicity: p^2 is included in P_2, and p^3 and p^2 q are included in P_3 when their factors exceed the cutoff. Nondecreasing factor order counts each integer once. When a = 0, all primes are allowed.

The methods use different cutoffs and correction terms:

The Legendre implementation and shared \Phi calculation build on Kim Walisch's work in primecount, including cached partial-sieve values, small-prime periodic tables, and prime-count lookup shortcuts.

Value

A single whole number giving the number of primes less than or equal to n. The result has type integer when it is at most .Machine$integer.max, and type double otherwise. The count is exact throughout the supported range.

Note

The counting methods prepare tables with storage proportional to \sqrt n. At the maximum input 2^{53} - 1, the dense prime-count table requires about 362 MiB and the prime-vector reservation requests about 42 MiB, before caches and other overhead. These are calculated storage estimates, not measured peak memory. Workers within one call share the tables; concurrent calls prepare separate tables. The supported numeric range does not guarantee that every input is practical for available memory.

Author(s)

Joseph Wood

References

See Also

primeSieve, nthPrime, primePhi, semiPrimeCount, triPrimeCount

Examples

## Get the number of primes less than or equal to a billion
primeCount(10^9)

## Select a method explicitly
primeCount(10^6, method = "legendre")
primeCount(10^6, method = "meissel")
primeCount(10^6, method = "lehmer")

## Using nThreads
system.time(primeCount(10^10, nThreads = 2, method = "lehmer"))

Vectorized Prime Factorization

Description

Implementation of Pollard's rho algorithm for generating the prime factorization. The algorithm is based on the "factorize.c" source file from the gmp library found here https://gmplib.org.

Usage

primeFactorize(v, namedList = FALSE, nThreads = NULL)

Arguments

v

Vector of integers or numeric values. Non-integral values will be cured to whole numbers.

namedList

Logical flag. If TRUE and the length(v) > 1, a named list is returned. The default is FALSE.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

As noted in the Description section above, this algorithm is based on the "factorize.c" source code from the gmp library. Much of the code in RcppAlgos::primeFactorize is a straightforward translation from multiple precision C data types to standard C++ data types. A crucial part of the algorithm's efficiency is based on quickly determining primality, which is easily computed with gmp. However, with standard C++, this is quite challenging. Much of the research for RcppAlgos::primeFactorize was focused on developing an algorithm that could accurately and efficiently compute primality.

For more details, see the documentation for isPrimeRcpp.

Value

Note

The maximum value for each element in v is 2^{53} - 1.

Author(s)

Joseph Wood

References

See Also

primeFactorizeSieve, factorize

Examples

## Get the prime factorization of a single number
primeFactorize(10^8)

## Or get the prime factorization of many numbers
set.seed(29)
myVec <- sample(-1000000:1000000, 1000)
system.time(pFacs <- primeFactorize(myVec))

## Return named list
pFacsWithNames <- primeFactorize(myVec, namedList = TRUE)

## Using nThreads
system.time(primeFactorize(myVec, nThreads = 2))

Generate Prime Factorization for Numbers in a Range

Description

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

Usage

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

Arguments

bound1

Positive integer or numeric value.

bound2

Positive integer or numeric value.

namedList

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

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

Details

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 https://libdivide.com/:

Value

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

Note

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

Author(s)

Joseph Wood

References

See Also

primeFactorize, divisorsSieve, factorize

Examples

## Generate some random data
set.seed(28)
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))

Count Integers Remaining After a Partial Prime Sieve

Description

Count the positive integers less than or equal to n that are not divisible by any of the first a primes. This is the partial-sieve function \Phi(n, a) used in combinatorial prime counting, not Euler's totient function.

Usage

primePhi(n, a, nThreads = NULL)

Arguments

n

A single nonnegative whole number, at most 2^{53} - 1.

a

A single nonnegative whole number, at most 2^{53} - 1. This is the number of initial primes to exclude, not a prime value or an upper bound on the excluded primes. For example, a = 3 excludes multiples of 2, 3, and 5. With a = 0, no primes are excluded.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. This argument is validated even when the result is immediate.

Details

Logical inputs FALSE and TRUE are converted to 0 and 1, respectively. The thread count must be positive, so nThreads = FALSE is not supported.

Mathematical definition

Write p_1 = 2, p_2 = 3, p_3 = 5, \ldots for the increasing sequence of primes. Then \Phi(n, a) counts integers m with 1 \le m \le n for which none of p_1, \ldots, p_a divides m. When a = 0, the excluded set is empty. In particular,

\Phi(n, 0) = n, \qquad \Phi(0, a) = 0.

For a \ge 1, removing multiples of the next prime gives

\Phi(n, a) = \Phi(n, a - 1) - \Phi(\lfloor n / p_a \rfloor, a - 1).

The subtracted term counts the multiples of p_a that survived removal of the preceding primes.

The integer 1 survives every partial sieve. Thus, when n > 0, the answer is at least 1, and it is exactly 1 when a \ge \pi(n), where \pi(n) is the number of primes at most n. Composite numbers can also survive: for example, primePhi(30, 2) includes 25 because neither 2 nor 3 divides it. This gives the ten survivors 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.

Euler's totient \phi(n) instead counts integers at most n that are coprime to n itself. For that function, see eulerPhiSieve.

Relation to prime counting

If a = \pi(\lfloor \sqrt n \rfloor) and n \ge 1, every surviving integer other than 1 is a prime larger than the excluded primes. Legendre's formula is therefore

\pi(n) = \Phi(n, a) + a - 1.

Smaller choices of a leave composite survivors. Meissel and Lehmer prime counting account for these using the correction terms exposed by semiPrimeCount and triPrimeCount. See primeCount for the corresponding formulas.

Value

A single whole number giving \Phi(n, a). The result has type integer when it is at most .Machine$integer.max, and type double otherwise. The count is exact throughout the supported range.

Note

The general calculation prepares prime and prime-count tables with storage proportional to \sqrt n. Cases with a \le 6 use small periodic tables instead of a full square-root table. Large values of a do not require preparing all of the first a primes merely to establish that the answer is 1.

The largest supported table limit is 94,906,265. Its dense prime-count table alone requires 4(L + 1) bytes for limit L, about 362 MiB at that maximum. Prime vectors, the shared Phi cache, temporary storage, and allocation overhead require additional memory. Workers within one call share the prepared tables; separate calls prepare their own tables. The numeric input range does not guarantee that every calculation is practical for the available resources.

Author(s)

Joseph Wood

See Also

primeCount, semiPrimeCount, triPrimeCount, eulerPhiSieve, primeSieve

Examples

## Remove multiples of the first two primes, 2 and 3
primePhi(30, 2)  ## 10

## No excluded primes; an empty interval; all primes through n excluded
primePhi(30, 0)   ## 30
primePhi(0, 2)    ## 0
primePhi(30, 100) ## 1

## Recover the prime count using Legendre's formula
n <- 1000
a <- primeCount(floor(sqrt(n)))
primePhi(n, a) + a - 1 == primeCount(n)

Generate or Count Prime Numbers

Description

Implementation of the segmented sieve of Eratosthenes with wheel factorization. Generates all prime numbers between bound1 and bound2 (if supplied) or all primes up to bound1. Set countOnly = TRUE to return the number of primes in the same interval without storing the generated primes. Both endpoints are included. See this stackoverflow post for an analysis on prime number generation efficiency in R: Generate a list of primes up to a certain number

The fundamental concepts of this algorithm are based off of the implementation by Kim Walisch found here: kimwalisch/primesieve.

Usage

primeSieve(bound1, bound2 = NULL, nThreads = NULL, countOnly = FALSE)

Arguments

bound1

Positive integer or numeric value.

bound2

Positive integer or numeric value.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads.

countOnly

Logical value. If TRUE, returns only the number of primes in the interval. The default is FALSE, which returns the primes themselves.

Details

When countOnly = TRUE, the same segmented sieve counts the surviving primes directly. This avoids allocating a vector of all primes in the interval, but the sieving primes, sieve segments, and other working data still require memory. Parallel calculations may use additional working memory. Counting is particularly useful for short intervals with large bounds.

Counting still uses the sieve when bound2 is omitted. For the number of primes up to a large value, use primeCount, which also provides combinatorial prime-counting methods. Neither function counts 1 as prime.

At the heart of this algorithm is the traditional sieve of Eratosthenes (i.e. given a prime p, mark all multiples of p as composite), however instead of sieving the entire interval, we only consider small sub-intervals. The benefits of this method are two fold:

  1. Reduction of the space complexity from O(n), for the traditional sieve, to O(\sqrt n)

  2. Reduction of cache misses

The latter is of particular importance as cache memory is much more efficient and closer in proximity to the CPU than main memory. Reducing the size of the sieving interval allows for more effective utilization of the cache, which greatly impacts the overall efficiency.

Another optimization over the traditional sieve is the utilization of wheel factorization. With the traditional sieve of Eratosthenes, you typically check every odd index of your logical vector and if the value is true, you have found a prime. With wheel factorization using the first four primes (i.e. 2, 3, 5, and 7) to construct your wheel (i.e. 210 wheel), you only have to check indices of your logical vector that are coprime to 210 (i.e. the product of the first four primes). As an example, with n = 10000 and a 210 wheel, you only have to check 2285 indices vs. 5000 with the classical implementation.

Value

When countOnly = FALSE, returns an integer vector if max(bound1, bound2) < 2^{31}, or a numeric vector otherwise.

When countOnly = TRUE, returns a single integer if the count is at most .Machine$integer.max, or a single numeric value otherwise. The count is exact throughout the supported range, and an interval containing no primes returns 0L. The count's type depends on the number of primes, not the magnitude of the bounds.

Note

Author(s)

Joseph Wood

References

See Also

primeCount, isPrimeRcpp

Examples

## Primes up to a thousand
primeSieve(100)

## Primes between 42 and 17
primeSieve(42, 17)

## Equivalent to
primeSieve(17, 42)

## Count the primes without generating a vector
primeSieve(17, 42, countOnly = TRUE)

## Count primes in an interval with large bounds
primeSieve(1e10, 1e10 + 100, countOnly = TRUE)

## Count primes up to a hundred
primeSieve(100, countOnly = TRUE)

## Primes up to one hundred million in no time
system.time(primeSieve(10^8))

## options(scipen = 50)
## Generate large primes over interval
system.time(myPs <- primeSieve(10^13+10^6, 10^13))
## Object created is small
object.size(myPs)

## Using nThreads
system.time(primeSieve(1e7, nThreads = 2))

Count SemiPrimes With an Optional Partial-Sieve Cutoff

Description

Count positive integers less than or equal to n with exactly two prime factors, counted with multiplicity, excluding the first a primes as factors. This is the correction term P_2(n, a) used in Meissel and Lehmer prime counting.

Usage

semiPrimeCount(n, a = 0, nThreads = NULL)

Arguments

n

A single nonnegative whole number, at most 2^{53} - 1.

a

A single nonnegative whole number, at most 2^{53} - 1. This is the number of initial primes excluded as factors, not a prime value. The default, a = 0, permits every prime. For example, a = 1 excludes the prime 2, so only odd semiprimes are counted.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. This argument is validated even when the result is immediate.

Details

Logical inputs FALSE and TRUE are converted to 0 and 1, respectively. The thread count must be positive, so nThreads = FALSE is not supported.

Mathematical definition

Let p_i denote the ith prime. The function counts products p_i p_j \le n with a < i \le j. The ordering counts each integer once: 2 \cdot 3 and 3 \cdot 2 do not give two different semiprimes. Equal factors are allowed, so prime squares such as 4, 9, and 25 are included when their prime factor is permitted.

When a = 0, the excluded set is empty; no zeroth prime is needed. The ten semiprimes at most 30 are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. Excluding the first prime leaves 9, 15, 21, 25, so semiPrimeCount(30, 1) is 4.

Write \pi(t) for the number of primes at most t, and set b = \pi(\lfloor \sqrt n \rfloor). For a fixed smaller factor p_i, the larger factor has an index from i through \pi(\lfloor n / p_i \rfloor). Consequently,

P_2(n, a) = \sum_{i=a+1}^{b} \left[\pi(\lfloor n / p_i \rfloor) - i + 1\right].

A sum with no terms is zero. In particular, the answer is zero for n < 4 or a \ge b. Equivalently, the smallest permitted prime square must be at most n for any semiprime to qualify.

Relation to prime counting

For Meissel's cutoff a = \pi(\lfloor n^{1/3} \rfloor), the partial sieve leaves 1, the primes beyond the cutoff, and qualifying semiprimes. Thus, for n \ge 1,

\pi(n) = \Phi(n, a) + a - 1 - P_2(n, a).

The function primePhi supplies \Phi(n, a). Lehmer's smaller cutoff also requires triPrimeCount; see primeCount for the full formula.

Value

A single whole number giving P_2(n, a). The result has type integer when it is at most .Machine$integer.max, and type double otherwise. The count is exact throughout the supported range.

Note

The calculation prepares prime and prime-count tables with storage proportional to \sqrt n. Larger prime-count queries in the sum use the shared partial-sieve evaluator or a segmented sieve, selected according to the input, cutoff, and useful thread budget. The segmented sieve uses bounded buffers for each worker; the function does not allocate a dense table through n / p_{a+1}.

At the largest supported n, the square-root table has limit 94,906,265. Its dense prime-count entries alone require 4(L + 1) bytes for limit L, about 362 MiB at the maximum, excluding prime vectors, the shared Phi cache, temporary storage, and allocation overhead. Workers within one call share the prepared tables; separate calls prepare their own tables. A valid numeric input may still require substantial time or memory.

Author(s)

Joseph Wood

See Also

primePhi, triPrimeCount, primeCount, primeSieve

Examples

## Count all semiprimes, then exclude 2 as a factor
semiPrimeCount(30)    ## 10
semiPrimeCount(30, 1) ## 4

## Equal prime factors are included
semiPrimeCount(4)     ## 1, from 2 * 2
semiPrimeCount(3)     ## 0
semiPrimeCount(0)     ## 0
semiPrimeCount(30, 100) ## 0

## A modest calculation with a requested thread budget
semiPrimeCount(10^6, nThreads = 2)

Max Number of Concurrent Threads

Description

Wrapper of std::thread::hardware_concurrency(). As stated by cppreference, the returned value should be considered only a hint.

Usage

stdThreadMax()

Value

An integer representing the number of concurrent threads supported by the user implementation. If the value cannot be determined, 1L is returned.

See Also

detectCores

Examples

stdThreadMax()

Count TriPrimes With an Optional Partial-Sieve Cutoff

Description

Count positive integers less than or equal to n with exactly three prime factors, counted with multiplicity, excluding the first a primes as factors. This is the correction term P_3(n, a) used in Lehmer prime counting. Its table requirements impose an additional input-dependent limit described below.

Usage

triPrimeCount(n, a = 0, nThreads = NULL)

Arguments

n

A single nonnegative whole number, at most 2^{53} - 1. The additional table limit in ‘Details’ may restrict the accepted value for a given a. With the default a = 0, the largest accepted n is 379,625,063.

a

A single nonnegative whole number, at most 2^{53} - 1. This is the number of initial primes excluded as factors, not a prime value. The default, a = 0, permits every prime. For example, a = 1 excludes the prime 2, so only odd triprimes are counted. Larger cutoffs can permit larger n within the table limit.

nThreads

Requested number of threads. The default is NULL for serial execution. Requests are capped by the available hardware and the useful work in the calculation. Small or simple cases may use fewer threads. This argument is validated even when the result is immediate.

Details

Logical inputs FALSE and TRUE are converted to 0 and 1, respectively. The thread count must be positive, so nThreads = FALSE is not supported.

Mathematical definition

Let p_i denote the ith prime. The function counts products p_i p_j p_k \le n with a < i \le j \le k. Nondecreasing factor order counts each integer once. Factors need not be distinct: prime cubes p^3 and products p^2 q are included, as are products of three different primes.

When a = 0, the excluded set is empty; no zeroth prime is needed. The seven triprimes at most 30 are 8, 12, 18, 20, 27, 28, 30. For example, 8 qualifies as 2^3, while 16 does not qualify because 2^4 has four prime factors counted with multiplicity. Excluding 2 leaves only 27 among these seven values.

Write \pi(t) for the number of primes at most t, and define

c = \pi(\lfloor n^{1/3} \rfloor), \qquad b_i = \pi(\lfloor \sqrt{n / p_i} \rfloor).

The smallest factor has index at most c; for that factor, the middle factor has index at most b_i. Once these two factors are fixed, the largest factor has index from j through \pi(\lfloor n / (p_i p_j) \rfloor). Hence,

P_3(n, a) = \sum_{i=a+1}^{c} \sum_{j=i}^{b_i} \left[\pi(\lfloor n / (p_i p_j) \rfloor) - j + 1\right].

A sum with no terms is zero. In particular, the answer is zero for n < 8 or a \ge c: the smallest permitted prime cube then exceeds n.

Relation to prime counting

At Lehmer's cutoff a = \pi(\lfloor n^{1/4} \rfloor), the surviving composites have two or three permitted prime factors. For n \ge 1,

\pi(n) = \Phi(n, a) + a - 1 - P_2(n, a) - P_3(n, a).

The other terms are available through primePhi and semiPrimeCount. See primeCount for the complete counting methods.

Table limit and memory use

The implementation first prepares tables through \lfloor n^{1/3} \rfloor to determine whether any qualifying triples exist. If they do, let p_{a+1} be the smallest permitted prime. Direct prime-count lookups require a table through

q_{\max} = \lfloor n / p_{a+1}^2 \rfloor.

Every queried quotient is at most this value. The largest supported table limit is 94,906,265; a nonempty calculation requiring a larger table raises an error before that larger table is allocated. An empty count does not require this second table.

With a = 0, the smallest permitted prime is 2, so the condition is \lfloor n / 4 \rfloor \le 94906265. This explains the default upper limit 379625063. Excluding more primes can reduce the required table size and allow larger inputs, up to the common numeric limit 2^{53} - 1 when the table condition is met.

Table storage is proportional to \max(n^{1/3}, n / p_{a+1}^2) for nonempty calculations. The dense prime-count entries alone use 4(L + 1) bytes for limit L, about 362 MiB at the maximum. This excludes prime vectors, temporary tables, worker storage, allocation overhead, and any shared Phi cache retained from other calls; it is not a peak-memory bound. Workers within one call share the prepared lookup tables. Inputs below the enforced table limit can still be expensive in time or memory.

Value

A single whole number giving P_3(n, a). The result has type integer when it is at most .Machine$integer.max, and type double otherwise. The count is exact for accepted inputs.

Author(s)

Joseph Wood

See Also

primePhi, semiPrimeCount, primeCount, primeSieve

Examples

## Count all triprimes, then exclude 2 as a factor
triPrimeCount(30)    ## 7
triPrimeCount(30, 1) ## 1, from 3 * 3 * 3

## Repeated prime factors are included
triPrimeCount(8)      ## 1, from 2 * 2 * 2
triPrimeCount(7)      ## 0
triPrimeCount(0)      ## 0
triPrimeCount(30, 100) ## 0

## Keep exploration modest: the default table extends through floor(n / 4)
triPrimeCount(10^5, nThreads = 2)

mirror server hosted at Truenetwork, Russian Federation.