Problem 9 » 履歴 » バージョン 6
Noppi, 2023/12/29 12:15
1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
---|---|---|---|
2 | # [[Problem 9]] |
||
3 | |||
4 | 3 | Noppi | ## Special Pythagorean Triplet |
5 | A Pythagorean triplet is a set of three natural numbers, $a \lt b \lt c$, for which, |
||
6 | $$a^2 + b^2 = c^2.$$ |
||
7 | For example, $3^2 + 4^2 = 9 + 16 = 25 = 5^2$. |
||
8 | There exists exactly one Pythagorean triplet for which $a + b + c = 1000$. |
||
9 | Find the product $abc$. |
||
10 | |||
11 | ## 特別なピタゴラス数 |
||
12 | ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である. |
||
13 | $$a^2 + b^2 = c^2.$$ |
||
14 | 例えば, $3^2 + 4^2 = 9 + 16 = 25 = 5^2$ である. |
||
15 | a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する. |
||
16 | これらの積 abc を計算しなさい. |
||
17 | |||
18 | 1 | Noppi | ```scheme |
19 | #!r6rs |
||
20 | #!chezscheme |
||
21 | |||
22 | (import (chezscheme)) |
||
23 | |||
24 | 4 | Noppi | (define sum-1000-triplets |
25 | (let loop1 ([a 1] [result '()]) |
||
26 | 6 | Noppi | (if (< 332 a) |
27 | 4 | Noppi | result |
28 | 6 | Noppi | (let loop2 ([b (add1 a)] [result result]) |
29 | 1 | Noppi | (if (< 499 b) |
30 | 4 | Noppi | (loop1 (add1 a) result) |
31 | 1 | Noppi | (let ([c (- 1000 a b)]) |
32 | 4 | Noppi | (loop2 (add1 b) (cons `(,a ,b ,c) result)))))))) |
33 | |||
34 | (define (pythagorean? a b c) |
||
35 | (= (+ (expt a 2) (expt b 2)) |
||
36 | (expt c 2))) |
||
37 | |||
38 | (define pythagorean-triplets |
||
39 | (filter |
||
40 | (lambda (lis) |
||
41 | (apply pythagorean? lis)) |
||
42 | sum-1000-triplets)) |
||
43 | |||
44 | 1 | Noppi | (define answer-9 |
45 | 5 | Noppi | (begin |
46 | (assert (= (length pythagorean-triplets) 1)) |
||
47 | (apply * (car pythagorean-triplets)))) |
||
48 | 1 | Noppi | |
49 | (printf "9: ~D~%" answer-9) |
||
50 | ``` |