Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

algorithm - how to find consecutive composite numbers in R

I want first 'n' consecutive composite numbers

I searched command for finding consecutive composite numbers, but i got the result proving for that thorem. I didn't get any command for that..please help me to slove this problem in R.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is another option:

n_composite <- function(n) {

  s <- 4L
  i <- 1L
  vec <- numeric(n)
  while(i <= n) {

    if(any(s %% 2:(s-1) == 0L)) {
      vec[i] <- s
      i <- i + 1L

    }

    s <- s + 1L
  }

  vec
}

It uses basic control flows to cycle through positive integers indexing composites.

benchmark

all.equal(find_N_composites(1e4), n_composite(1e4))
[1] TRUE

library(microbenchmark)
microbenchmark(

  Mak = find_N_composites(1e4),
  plafort = n_composite(1e4),
  times=5

  )

Unit: milliseconds
    expr       min        lq      mean    median        uq
     Mak 2304.8671 2347.9768 2397.0620 2376.4306 2475.2368
 plafort  508.8132  509.3055  522.1436  509.3608  530.4311
       max neval cld
 2480.7988     5   b
  552.8076     5  a 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...