プロジェクト

全般

プロフィール

操作

Problem 4 » 履歴 » リビジョン 5

« 前 | リビジョン 5/6 (差分) | 次 »
Noppi, 2023/12/28 02:06


ホーム - Project Euler

Problem 4

Largest Palindrome Product

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$.
Find the largest palindrome made from the product of two $3$-digit numbers.

最大の回文積

左右どちらから読んでも同じ値になる数を回文数という. 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である.
では, 3桁の数の積で表される回文数の最大値を求めよ.

#!r6rs
#!chezscheme

(import (chezscheme))

(define (palindrome? num)
  (let* ([num-string (number->string num)]
         [str-length (string-length num-string)]
         [count (div str-length 2)])
    (let loop ([index 0])
      (cond
        [(<= count index) #t]
        [(char=?
           (string-ref num-string index)
           (string-ref num-string (- str-length 1 index)))
         (loop (add1 index))]
        [else #f]))))

(define iota-3digits
  (filter
    (lambda (n) (<= 100 n))
    (iota 1000)))

(define product-3digits-numbers
  (fold-left
    (lambda (lis current)
      (let loop ([result lis]
                 [temp (map
                         (lambda (n) (* n current))
                         iota-3digits)])
        (if (null? temp)
          result
          (loop (cons (car temp) result) (cdr temp)))))
    '()
    iota-3digits))

(define palindrome-product-3digits-numbers
  (filter palindrome? product-3digits-numbers))

(define answer-4
  (apply max palindrome-product-3digits-numbers))

(printf "4: ~D~%" answer-4)

Noppi2023/12/28に更新 · 5件の履歴