typestar

Primality test in R

Trial division, written vectorized so it tests a whole vector at once.

is_prime <- function(n) {
  if (n < 2) {
    return(FALSE)
  }
  if (n < 4) {
    return(TRUE)
  }
  divisors <- 2:floor(sqrt(n))
  all(n %% divisors != 0)
}

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
137
Tokens
51
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 36 seconds.

Type this snippet

Step 3 of 5 in Flow & functions, step 7 of 20 in Language basics.

← Previous Next →

Primality test in other languages