R and Python Functions For Detecting Prime Numbers

R function:

is_prime <- function(x) {
  !any(x %% 2:(x-1) == 0L)
}

Examples:

is_prime(7)
## [1] TRUE
is_prime(934213)
## [1] FALSE
is_prime(934213)
## [1] FALSE
is_prime(999983)
## [1] TRUE

Python function:

import numpy as np
def is_prime_python(x):
    return not any(x % np.arange(2,x-1) == 0)

Examples:

is_prime_python(7)
## True
is_prime_python(934213)
## False
is_prime_python(934213)
## False
is_prime_python(999983)
## True
Dave Rosenman
Dave Rosenman
Senior Business Analyst

Related