Learn R Programming

SDraw (version 2.1.13)

primes: Prime numbers

Description

Returns the first n prime numbers (starting at 2)

Usage

primes(n)

Arguments

n

Number prime numbers requested, starting at 2. Maximum is 1e8 or 100,000,000.

Value

A vector of length n containing prime numbers, in order, starting at 2. Note that 1 is prime, but is never included here. I.e., primes(1) equals c(2).

Details

This routine is brute-force and works well for the low primes, i.e., for n less than a couple hundred thousand. It is not particularly efficient for large n. For example, primes(2000) on a Windows laptop takes approximately 4 seconds, while primes(5000) takes approximately 30 seconds.

Examples

Run this code
# NOT RUN {
primes(4) #  c(2,3,5,7)    

# Prime pairs in the first 100
p <- primes(100)
p.diff <- diff(p)
cbind(p[-length(p)][p.diff==2], p[-1][p.diff==2])
# }

Run the code above in your browser using DataLab