Project Euler

Author

Angel Alcala Ruiz

Published

November 20, 2023

Problem 7: 10001st Prime

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 10,001st prime number?

Code
function Prime(n)

#' @@name Prime
#' 
#' @@description 
#' 
#' This function finds the nth prime numbers
#'
#' @@arg n: A positive integer n
#'
#' @@return The nth prime number
#'
#' @@examples
#'
#' n = 13
#' Prime(n)

    function is_prime(m)
    # This function checks if m is prime
    
        bool = true
        k = 2
        if m == 0
            bool = false
        elseif m == 1
            bool = false  
        elseif m == 2
            bool = true
        end
    
        while k < m
            if m%k == 0
                bool = false
                break
            end
            k = k + 1
        end
        return bool
    end

    prime_vector = []
    i = 0

    while true

        if is_prime(i)
            prime_vector = push!(prime_vector, i)
        end
        
        if length(prime_vector) == n
            break
        end
        i = i + 1
    end

    prime = prime_vector[n]
    
    return prime
end
Prime (generic function with 1 method)

Let’s now test our code with the given example

Code
Prime(6)
13

Therefore we can see that the 6th prime number is 13 which is correct.

Let’s now find the 10,001st prime number

Code
Prime(10001)
104743

Therefore we have that the 10,001st prime number is 104,743.