Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active March 30, 2019 10:03
Show Gist options
  • Save nilforooshan/8be3c036ada3f54315572e6dc160048e to your computer and use it in GitHub Desktop.
Save nilforooshan/8be3c036ada3f54315572e6dc160048e to your computer and use it in GitHub Desktop.
R: Find prime numbers in an array

R function to find prime numbers in an array

The functions:

check.integer <- function(x) { x == round(x) }
 
is.prime <- function(y) { !check.integer(y/2) &
                          !check.integer(y/3) &
                          !check.integer(y/5) &
                          !check.integer(y/7) }
 
find.primes <- function(z) { z <- z[z > 1]
                             primes <- c(2,3,5,7)
                             primes <- primes[primes >= min(z)]
                             for(i in z) { if(is.prime(i)==TRUE) primes <- c(primes,i) }
                             print(primes) }

Example:

find.primes(7:37)

Output:

[1]  7 11 13 17 19 23 29 31 37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment