r - Understanding the behaviour of subsetting using 'which' -


i trying define function generating prime numbers till n. came following solution, compared solution readily available (given below reference). there's line of difference in both codes (indicated below)

sieve <- function(n){ sq.n <- sqrt(n) vec <- 2:n primes <- rep(0, times=(sq.n)) <- 1 while (!(is.na(primes[i] < sq.n)) && (primes[i]) < (sq.n)) {     primes[i] <- vec[1]     vec <- vec[which(vec%%primes[i] != 0)] # keeps numbers not divisible      # prime in question     <- + 1 } return(c(primes[which(primes!=0)], vec)) } 

curious efficiency, google search yielded following code -

getprimenumtilln <- function(n) { <- c(2:n) l <- 2 r <- c() while (l*l < n) {     r <- c(r,a[1])     <- a[-(which(a %% l ==0))] # removes numbers      # divisible prime in question     l <- a[1] } c(r,a) } 

both solutions work okay. (the internet solution gives wrong answer if n square of prime, can corrected easily)

and these microbenchmark results -

microbenchmark(sieve(100),getprimenumtilln(100),times=100) unit: microseconds                   expr     min      lq      mean  median      uq     max neval             sieve(100) 142.107 153.106 165.85155 162.785 165.425 466.795   100  getprimenumtilln(100)  41.797  47.076  51.09312  49.276  51.036 126.269   100 

i understand fair difference in runtime of both functions

the loop of first function 10 iterations n = 100, second function 4.

sieve <- function(n){   sq.n <- sqrt(n)   vec <- 2:n   primes <- rep(0, times=(sq.n))   <- 1   while (!(is.na(primes[i] < sq.n)) && (primes[i]) < (sq.n)) {     count <<- count + 1     primes[i] <- vec[1]     vec <- vec[which(vec%%primes[i] != 0)] # keeps numbers not divisible      # prime in question     <- + 1   }   return(c(primes[which(primes!=0)], vec)) }  count <- 0 sieve(100) #[1]  2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 count #[1] 10  getprimenumtilln <- function(n) {   <- c(2:n)   l <- 2   r <- c()   while (l*l < n) {     count <<- count + 1     r <- c(r,a[1])     <- a[-(which(a %% l ==0))] # removes numbers      # divisible prime in question     l <- a[1]   }   c(r,a) }  count <- 0 getprimenumtilln(100) # [1]  2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 count #[1] 4 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -