プロジェクト

全般

プロフィール

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

Noppi, 2023/12/27 04:55

1 1 Noppi
[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]]
2
# [[Problem 10]]
3
4
```scheme
5
#!r6rs
6
#!chezscheme
7
8
(import (chezscheme))
9
10 2 Noppi
(define (sum-prime prime?-table)
11 4 Noppi
  (let* ([len (vector-length prime?-table)]
12
         [index-list (iota len)]
13
         [prime?-list (vector->list prime?-table)])
14 2 Noppi
    (fold-left
15
      (lambda (sum index prime?)
16
        (if prime?
17
          (+ sum index)
18
          sum))
19
      0
20
      index-list
21
      prime?-list)))
22
23 3 Noppi
(define (eratosthenes-sub! table erase-num)
24
  (assert (vector-ref table erase-num))
25 4 Noppi
  (let loop ([current (* erase-num 2)])
26 3 Noppi
    (cond
27
      [(<= (vector-length table) current) table]
28
      [else
29
        (vector-set! table current #f)
30
        (loop (+ current erase-num))])))
31
32
(define (eratosthenes num)
33 4 Noppi
  (let ([table (make-vector num #t)]
34
        [count (isqrt (sub1 num))])
35 1 Noppi
    (vector-set! table 0 #f)
36
    (vector-set! table 1 #f)
37 4 Noppi
    (let loop ([index 2] [table table])
38 3 Noppi
      (cond
39 1 Noppi
        [(< count index) table]
40 3 Noppi
        [(vector-ref table index)
41 1 Noppi
         (loop (add1 index) (eratosthenes-sub! table index))]
42 3 Noppi
        [else (loop (add1 index) table)]))))
43
44 4 Noppi
;;; Problem 10
45 3 Noppi
(define answer-10
46
  (sum-prime (eratosthenes 2000001)))
47 1 Noppi
48
(printf "10: ~D~%" answer-10)
49
```