プロジェクト

全般

プロフィール

Problem 10 » 履歴 » バージョン 8

Noppi, 2023/12/28 07:51

1 1 Noppi
[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]]
2
# [[Problem 10]]
3
4 6 Noppi
## Summation of Primes
5
The sum of the primes below $10$ is $2 + 3 + 5 + 7 = 17$.
6
Find the sum of all the primes below two million.
7
8
## 素数の和
9
10以下の素数の和は 2 + 3 + 5 + 7 = 17 である.
10
200万以下の全ての素数の和を求めよ.
11
12 1 Noppi
```scheme
13
#!r6rs
14
#!chezscheme
15 4 Noppi
16
(import (chezscheme))
17 2 Noppi
18 7 Noppi
(define (eratosthenes-sub1! table erase-num)
19 1 Noppi
  (assert (vector-ref table erase-num))
20
  (let loop ([current (* erase-num 2)])
21
    (cond
22
      [(<= (vector-length table) current) table]
23
      [else
24
        (vector-set! table current #f)
25 6 Noppi
        (loop (+ current erase-num))])))
26 1 Noppi
27 7 Noppi
(define (eratosthenes-sub2 table)
28 8 Noppi
  (filter
29
    (lambda (num-or-f)
30
      (or num-or-f #f))
31
    (vector->list table)))
32 7 Noppi
33 1 Noppi
(define (eratosthenes num)
34 7 Noppi
  (let ([table (list->vector (iota num))]
35 1 Noppi
        [count (isqrt (sub1 num))])
36 4 Noppi
    (vector-set! table 0 #f)
37 3 Noppi
    (vector-set! table 1 #f)
38 1 Noppi
    (let loop ([index 2] [table table])
39 3 Noppi
      (cond
40 7 Noppi
        [(< count index) (eratosthenes-sub2 table)]
41 3 Noppi
        [(vector-ref table index)
42 7 Noppi
         (loop (add1 index) (eratosthenes-sub1! table index))]
43 3 Noppi
        [else (loop (add1 index) table)]))))
44
45 1 Noppi
(define answer-10
46 7 Noppi
  (apply + (eratosthenes 2000001)))
47 1 Noppi
48
(printf "10: ~D~%" answer-10)
49
```