Skip to content

Instantly share code, notes, and snippets.

@ponkore
Created April 24, 2012 13:09
Show Gist options
  • Save ponkore/2479526 to your computer and use it in GitHub Desktop.
Save ponkore/2479526 to your computer and use it in GitHub Desktop.
Project Euler Problem 4
;;;A palindromic number reads the same both ways.
;;;The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.
;;;Find the largest palindrome made from the product of two 3-digit numbers.
;;;左右どちらから読んでも同じ値になる数を回文数という。 2桁の数の積で表される回文数のうち、
;;;最大のものは 9009 = 91 × 99 である。
;;;では、3桁の数の積で表される回文数のうち最大のものはいくらになるか。
;;; 回文判定
(defn palindromic? [str]
(let [len (count str)]
(cond (<= len 1) true
(= (first str) (last str)) (palindromic? (subs str 1 (dec (count str))))
:else false)))
;;;(palindromic? "abc")
;;;=>false
;;;(palindromic? "aba")
;;;=>true
;;;(palindromic? "aabaa")
;;;=>true
;;;(palindromic? "aaba")
;;;=>false
;;;(palindromic? "a")
;;;=>true
;;;(palindromic? "")
;;;=>true
;;;user> (palindromic? (str 0))
;;;true
;;;user> (palindromic? (str 10))
;;;false
;;;user> (palindromic? (str 101))
;;;true
;;;user> (palindromic? (str 1001))
;;;true
;;;user> (palindromic? (str 1002))
;;;false
;;;user>
(def dig3nums (take-while #(< % 1000) (iterate inc 100)))
;;;
(apply min dig3nums)
;;;=>100
(apply max dig3nums)
;;;=>999
(* 999 999)
;;;=>998001
;;; よって、最大でも6桁までの回文数を求めれば良い。
;;;総当り攻撃w
(for [x dig3nums y dig3nums :when (palindromic? (str (* x y)))] [x y (* x y)])
;;;=> ([101 101 10201] [101 111 11211] [101 121 12221] [101 131 13231] [101 141 14241] ...
;;; ... [995 517 514415] [995 583 580085])
;;;最大の値を求める
(apply max (for [x dig3nums y dig3nums :when (palindromic? (str (* x y)))] (* x y)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment