Problem 10 » 履歴 » バージョン 3
Noppi, 2023/12/27 04:04
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 | (let* ((len (vector-length prime?-table)) |
||
12 | (index-list (iota len)) |
||
13 | (prime?-list (vector->list prime?-table))) |
||
14 | (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 | (let loop ((current (* erase-num 2))) |
||
26 | (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 | (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 | 3 | Noppi | (let loop ((index 2) (table table)) |
38 | 1 | Noppi | (cond |
39 | 3 | Noppi | [(< count index) table] |
40 | 1 | Noppi | [(vector-ref table index) |
41 | 3 | Noppi | (loop (add1 index) (eratosthenes-sub! table index))] |
42 | [else (loop (add1 index) table)])))) |
||
43 | |||
44 | (define answer-10 |
||
45 | (sum-prime (eratosthenes 2000001))) |
||
46 | 1 | Noppi | |
47 | (printf "10: ~D~%" answer-10) |
||
48 | ``` |