开发者

What is an elegant way to find all prime numbers in a specified range in R? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Generate a list of primes in R up to a certain number

What are elegant way开发者_如何学Pythons to find all prime numbers in a specified range in R language?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜