2018-4-1

Finding the 10001st prime with R

Solution to the seventh Project Euler problem – 10001st prime - in R.

The seventh Project Euler problem - 10001st prime - is stated as follows. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?

isPrime <- function(n) {
  if (n == 2 || n == 3) {
    # Handle the edge cases 2 and 3.
    return(TRUE)                    
  } else if (n < 2 || n %% 2 == 0) {
    # Check if n is less than 2 or equal to a multiple of 2.
    return(FALSE)
  } else {
    # Factors come in pairs and one of the factors has
    # to be smaller than the square root of N.
    upper.limit <- floor(sqrt(n))
    range <- seq(3, upper.limit)

    # Check if N is divisible 
    d <- n %% (range)

    # PRIME = Nothing in range is divisble by N.
    # NOT PRIME = Something in range is divisible by N.
    return(! 0%in%d)
  }
}

# Init target prime, a counter and an empty vector.
target <- 10001
current <- 1
primes <- c()

# Find primes untill we have TARGET primes.
while (length(primes) < target) {
  primes = if (isPrime(current)) c(primes, current) else primes
  current = current + 1
}

# Print the prime we are looking for.
sprintf("The %sth prime is %s", target, primes[target])
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.