Problem 4 » 履歴 » バージョン 5
Noppi, 2023/12/28 02:06
1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
---|---|---|---|
2 | # [[Problem 4]] |
||
3 | |||
4 | 4 | Noppi | ## Largest Palindrome Product |
5 | A palindromic number reads the same both ways. The largest palindrome made from the product of two $2$-digit numbers is $9009 = 91 \times 99$. |
||
6 | Find the largest palindrome made from the product of two $3$-digit numbers. |
||
7 | |||
8 | ## 最大の回文積 |
||
9 | 左右どちらから読んでも同じ値になる数を回文数という. 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である. |
||
10 | では, 3桁の数の積で表される回文数の最大値を求めよ. |
||
11 | |||
12 | 1 | Noppi | ```scheme |
13 | #!r6rs |
||
14 | #!chezscheme |
||
15 | |||
16 | (import (chezscheme)) |
||
17 | |||
18 | 5 | Noppi | (define (palindrome? num) |
19 | 3 | Noppi | (let* ([num-string (number->string num)] |
20 | [str-length (string-length num-string)] |
||
21 | [count (div str-length 2)]) |
||
22 | (let loop ([index 0]) |
||
23 | 1 | Noppi | (cond |
24 | [(<= count index) #t] |
||
25 | 5 | Noppi | [(char=? |
26 | 1 | Noppi | (string-ref num-string index) |
27 | (string-ref num-string (- str-length 1 index))) |
||
28 | 3 | Noppi | (loop (add1 index))] |
29 | 1 | Noppi | [else #f])))) |
30 | |||
31 | 5 | Noppi | (define iota-3digits |
32 | 4 | Noppi | (filter |
33 | 1 | Noppi | (lambda (n) (<= 100 n)) |
34 | 4 | Noppi | (iota 1000))) |
35 | 1 | Noppi | |
36 | 5 | Noppi | (define product-3digits-numbers |
37 | (fold-left |
||
38 | (lambda (lis current) |
||
39 | (let loop ([result lis] |
||
40 | [temp (map |
||
41 | (lambda (n) (* n current)) |
||
42 | iota-3digits)]) |
||
43 | (if (null? temp) |
||
44 | result |
||
45 | (loop (cons (car temp) result) (cdr temp))))) |
||
46 | '() |
||
47 | iota-3digits)) |
||
48 | 4 | Noppi | |
49 | 5 | Noppi | (define palindrome-product-3digits-numbers |
50 | (filter palindrome? product-3digits-numbers)) |
||
51 | 4 | Noppi | |
52 | 1 | Noppi | (define answer-4 |
53 | 5 | Noppi | (apply max palindrome-product-3digits-numbers)) |
54 | 1 | Noppi | |
55 | (printf "4: ~D~%" answer-4) |
||
56 | ``` |