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
functionPrimeSum(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)functionIsPrime(n)# This function checks whether an integer is prime bool =true k =2if n ==1 bool =falseelseif n ==2 bool =trueendwhile k < nif n%k ==0 bool =falsebreakend k = k +1endreturn boolend sum =0for i =1:nifIsPrime(i) sum = sum + iendendreturn sumend
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\).