Skip to content

Problem 10: Summation of primes

Link to the problem: https://projecteuler.net/problem=10.

Problem 10

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

Find the sum of all the primes below two million.

A simple solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
;; note: same as in problem 7
(defn isPrime []
  (-> (| (-> (ToFloat) (Math.Sqrt) (Math.Floor) (ToInt) >= .r
             5 >= .f
             true >= .isPrime))
      (| (When (Is 1) (-> false > .isPrime)))
      (| (When
          (-> (IsMore 2) (And) (Math.Mod 2) (Is 0))
          (-> false > .isPrime)))
      (| (When
          (-> (IsMore 3) (And) (Math.Mod 3) (Is 0))
          (-> false > .isPrime)))
      (When
       (-> .isPrime (And) .f (IsLessEqual .r))
       (Repeat
        (-> (When
             (-> (Math.Mod .f) (Is 0))
             (-> false > .isPrime))
            (When
             (-> (| (-> .f (Math.Add 2) >= .g))
                 (Math.Mod .g) (Is 0))
             (-> false > .isPrime))
            .f (Math.Add 6) > .f)
        :Forever true
        :Until (-> .isPrime (Not) (Or) .f (IsMore .r))))
      .isPrime))

(defwire main-wire
  2000000 = .limit
  5 >= .sum >= .n

  (Repeat
   (-> .n (When
           (isPrime)
           (-> .sum (Math.Add .n) > .sum))
       .n (Math.Add 2) > .n
       (When
        (-> .n (IsLessEqual .limit) (And) (isPrime))
        (-> .sum (Math.Add .n) > .sum))
       .n (Math.Add 4) > .n)
   :Forever true
   :Until (-> .n (IsMore .limit)))

  .sum
  (Log "Answer"))

(defmesh root)
(schedule root main-wire)
(run root)
[info] [2023-02-24 14:01:56.724] [T-2824] [logging.cpp::62] [main-wire] Answer: 142913828922

More details on the Project Euler's website: https://projecteuler.net/overview=010.