primeCount {RcppAlgos}R Documentation

Prime Counting Function π(x)\pi(x)

Description

Prime counting function for counting the prime numbers less than an integer, nn, using Legendre's formula. It is based on the the algorithm developed by Kim Walisch found here: kimwalisch/primecount.

Usage

primeCount(n, nThreads = NULL)

Arguments

n

Positive number

nThreads

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

Details

Legendre's Formula for counting the number of primes less than nn makes use of the inclusion-exclusion principle to avoid explicitly counting every prime up to nn. It is given by:

π(x)=π(x)+Φ(x,x)1\pi(x) = \pi(\sqrt x) + \Phi(x, \sqrt x) - 1

Where Φ(x,a)\Phi(x, a) is the number of positive integers less than or equal to xx that are relatively prime to the first aa primes (i.e. not divisible by any of the first aa primes). It is given by the recurrence relation (pap_a is the athath prime (e.g. p4=7p_4 = 7)):

Φ(x,a)=Φ(x,a1)+Φ(x/pa,a1)\Phi(x, a) = \Phi(x, a - 1) + \Phi(x / p_a, a - 1)

This algorithm implements five modifications developed by Kim Walisch for calculating Φ(x,a)\Phi(x, a) efficiently.

  1. Cache results of Φ(x,a)\Phi(x, a)

  2. Calculate Φ(x,a)\Phi(x, a) using Φ(x,a)=(x/pp)ϕ(pp)+Φ(xmodpp,a)\Phi(x, a) = (x / pp) * \phi(pp) + \Phi(x mod pp, a) if a<=6a <= 6

    • pp=23...pp = 2 * 3 * ... * prime[a]

    • ϕ(pp)=(21)(31)...\phi(pp) = (2 - 1) * (3 - 1) * ... * ((prime[a] 1)- 1) (i.e. Euler's totient function)

  3. Calculate Φ(x,a)\Phi(x, a) using π(x)\pi(x) lookup table

  4. Calculate all Φ(x,a)=1\Phi(x, a) = 1 upfront

  5. Stop recursion at 66 if x>=13\sqrt x >= 13 or π(x)\pi(\sqrt x) instead of 11

Value

Whole number representing the number of prime numbers less than or equal to nn.

Note

The maximum value of nn is 25312^{53} - 1

Author(s)

Joseph Wood

References

See Also

primeSieve

Examples

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

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

[Package RcppAlgos version 2.8.3 Index]