プロジェクト

全般

プロフィール

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

Noppi, 2023/12/29 04:14

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 6 Noppi
(define 3digits-combinations
37 5 Noppi
  (fold-left
38
    (lambda (lis current)
39
      (let loop ([result lis]
40
                 [temp (map
41 6 Noppi
                         (lambda (n) `(,current ,n))
42 5 Noppi
                         iota-3digits)])
43
        (if (null? temp)
44
          result
45
          (loop (cons (car temp) result) (cdr temp)))))
46 1 Noppi
    '()
47
    iota-3digits))
48 6 Noppi
49
(define product-3digits-numbers
50
  (map
51
    (lambda (lis) (apply * lis))
52
    3digits-combinations))
53 4 Noppi
54 5 Noppi
(define palindrome-product-3digits-numbers
55
  (filter palindrome? product-3digits-numbers))
56 4 Noppi
57 1 Noppi
(define answer-4
58 5 Noppi
  (apply max palindrome-product-3digits-numbers))
59 1 Noppi
60
(printf "4: ~D~%" answer-4)
61
```