プロジェクト

全般

プロフィール

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

Noppi, 2023/12/28 07:35

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
  (let-values ([(primes falses) (partition
29
                                  (lambda (num-or-f)
30
                                    (if num-or-f
31
                                      num-or-f
32
                                      #f))
33
                                  (vector->list table))])
34
    primes))
35
36 1 Noppi
(define (eratosthenes num)
37 7 Noppi
  (let ([table (list->vector (iota num))]
38 1 Noppi
        [count (isqrt (sub1 num))])
39 4 Noppi
    (vector-set! table 0 #f)
40 3 Noppi
    (vector-set! table 1 #f)
41 1 Noppi
    (let loop ([index 2] [table table])
42 3 Noppi
      (cond
43 7 Noppi
        [(< count index) (eratosthenes-sub2 table)]
44 3 Noppi
        [(vector-ref table index)
45 7 Noppi
         (loop (add1 index) (eratosthenes-sub1! table index))]
46 3 Noppi
        [else (loop (add1 index) table)]))))
47
48 1 Noppi
(define answer-10
49 7 Noppi
  (apply + (eratosthenes 2000001)))
50 1 Noppi
51
(printf "10: ~D~%" answer-10)
52
```