0

Possible Duplicate:
Generate a list of primes in R up to a certain number

What are elegant ways to find all prime numbers in a specified range in R language?

Community
  • 1
  • 1
Leonid
  • 22,360
  • 25
  • 67
  • 91
  • 3
    Is this question any different than this one? http://stackoverflow.com/questions/3789968/generate-a-list-of-primes-in-r-up-to-a-certain-number – Chase May 01 '11 at 13:21
  • @Chase: The two differences are that it asks for a range and it asks for "elegant ways" – Henry May 01 '11 at 21:57

1 Answers1

1

Here is a one line example which works in a narrow range: it is particularly important that the bottom of the range is more than the square root of the top. There can also be memory issues for wide ranges.

library(matrixStats)

pRange <- function(a,b) which(!rowCounts(!outer(a:b,2:sqrt(b),FUN="%%")))+a-1

For example

> pRange(1e8, 1e8+1e3)
 [1] 100000007 100000037 100000039 100000049 100000073 100000081 100000123
 [8] 100000127 100000193 100000213 100000217 100000223 100000231 100000237
[15] 100000259 100000267 100000279 100000357 100000379 100000393 100000399
[22] 100000421 100000429 100000463 100000469 100000471 100000493 100000541
[29] 100000543 100000561 100000567 100000577 100000609 100000627 100000643
[36] 100000651 100000661 100000669 100000673 100000687 100000717 100000721
[43] 100000793 100000799 100000801 100000837 100000841 100000853 100000891
[50] 100000921 100000937 100000939 100000963 100000969

In many cases it would probably be quicker to better to use John's version of a sieve from the earlier question and drop the unwanted lower values.

Community
  • 1
  • 1
Henry
  • 6,704
  • 2
  • 23
  • 39