Project Euler

Author

Angel Alcala Ruiz

Published

January 3, 2024

Problem 10: Summation of Primes

The sum of the primes below 10 is \(17 = 2 + 3 + 5 + 7\).

Find the sum of all the primes below two million.

Let’s solve using Julia

Code
function PrimeSum(n)

#' @@name PrimeSum
#'
#' @@description
#' 
#' This function sums all of the primes that are less than or equal to n
#'
#' @@arg n: A positive integer n
#' 
#' @@return The sum of all primes that are less than or equal to n
#'
#' @@examples

#' n = 10
#' PrimeSum(n)

    function IsPrime(n)
        # This function checks whether an integer is prime

        bool = true
        k = 2
        if n == 1
            bool = false
        elseif n == 2
            bool = true
        end
        
        while k < n
            if n%k == 0
                bool = false
                break
            end
            k = k + 1
        end
        return bool
    end

    sum = 0

    for i = 1:n
        if IsPrime(i)
            sum = sum + i
        end
    end
    return sum
end
PrimeSum (generic function with 1 method)

Let’s now check the given example

Code
PrimeSum(10)
17

Therefore we can see that the sum of all the primes below is 17.

Let’s now find the sum of all primes below two million

Code
PrimeSum(2000000)
142913828922

Therefore we get that the sum of the primes below two million is \(142,913,828,922\).