Regular expression for finding prime numbers
is.prime <- function(x) { x <- abs(as.integer(x)) !grepl('^1?$|^(11+?)\\1+$', strrep('1', x)) } (-100:100)[is.prime(-100:100)]
http://diswww.mit.edu/bloom-picayune.mit.edu/perl/10138
Or, if you take all integers from 1 to x , the number that is divisible without a remainder should be 2: 1 and x
is.prime <- function(x) vapply(x, function(y) sum(y / 1:y == y %/% 1:y), integer(1L)) == 2L (1:100)[is.prime(1:100)]
I knew regex would be the slowest, but it's still my favorite
is.prime <- function(x) vapply(x, function(y) sum(y / 1:y == y %/% 1:y), integer(1L)) == 2L is.prime_regex <- function(x) { x <- abs(as.integer(x)) !grepl('^1?$|^(11+?)\\1+$', strrep('1', x)) } is.prime_Seily <- function(n) vapply(n, function(y) y == 2L || all(y %% 2L:ceiling(sqrt(y)) != 0), logical(1L)) is.prime_flodel <- function(n) vapply(n, function(y) y == 2L || all(y %% 2L:max(2,floor(sqrt(y))) != 0), logical(1L)) x <- 1:1000 library('microbenchmark') microbenchmark( is.prime(x), is.prime_regex(x), is.prime_Seily(x), is.prime_flodel(x), unit = 'relative' ) # Unit: relative # expr min lq mean median uq max neval cld # is.prime(x) 8.593971 8.606353 8.805690 8.892905 9.724452 21.9886734 100 b # is.prime_regex(x) 84.572928 86.200415 76.413036 86.895956 85.117796 25.7106323 100 c # is.prime_Seily(x) 1.000000 1.000000 1.000000 1.000000 1.000000 1.0000000 100 a # is.prime_flodel(x) 1.146212 1.147971 1.144839 1.146119 1.163302 0.9085948 100 a
rawr
source share