プロジェクト

全般

プロフィール

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

Noppi, 2023/12/27 13:42

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 6 Noppi
(define (make-prime-list num)
19
  (fold-left
20
    (lambda (lis iota-num prime?)
21
      (if prime?
22
        (cons iota-num lis)
23
        lis))
24
    '()
25
    (iota num)
26
    (vector->list (eratosthenes num))))
27 3 Noppi
28 4 Noppi
(define (eratosthenes-sub! table erase-num)
29 3 Noppi
  (assert (vector-ref table erase-num))
30
  (let loop ([current (* erase-num 2)])
31
    (cond
32
      [(<= (vector-length table) current) table]
33
      [else
34
        (vector-set! table current #f)
35 4 Noppi
        (loop (+ current erase-num))])))
36
37 1 Noppi
(define (eratosthenes num)
38
  (let ([table (make-vector num #t)]
39
        [count (isqrt (sub1 num))])
40 4 Noppi
    (vector-set! table 0 #f)
41 3 Noppi
    (vector-set! table 1 #f)
42 1 Noppi
    (let loop ([index 2] [table table])
43 3 Noppi
      (cond
44 1 Noppi
        [(< count index) table]
45 3 Noppi
        [(vector-ref table index)
46
         (loop (add1 index) (eratosthenes-sub! table index))]
47
        [else (loop (add1 index) table)]))))
48
49 1 Noppi
(define answer-10
50 6 Noppi
  (apply + (make-prime-list 2000001)))
51 1 Noppi
52
(printf "10: ~D~%" answer-10)
53
```