Skip to content

Instantly share code, notes, and snippets.

@tnoda
Forked from ponkore/problem-4-1.clj
Created December 16, 2012 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnoda/4304116 to your computer and use it in GitHub Desktop.
Save tnoda/4304116 to your computer and use it in GitHub Desktop.
;;;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桁の数の積で表される回文数のうち最大のものはいくらになるか。
(ns projecteuler.problem-4
(:require [clojure.string :as str])
(:use clojure.test))
(defn palindromic?
"回文判定をする。"
[s] (= s (str/reverse s)))
(defn nseq
"n桁の数値シーケンスを作る。"
[n]
(let [seq-min (int (Math/pow 10 (dec n)))
seq-max (* seq-min 10)]
(range seq-min seq-max)))
(defn problem-4
"n桁×n桁の結果が回文数となる値を求める。"
([] (problem-4 3))
([n] (let [dig-seq (nseq n)]
(->> (for [x dig-seq y dig-seq] (* x y))
(filter (comp palindromic? str))
(apply max)))))
(time (problem-4))
;=> ???
;=> "Elapsed time: 255.488 msecs"
(time (problem-4 4))
;=> "Elapsed time: 24204.772 msecs"
;=> 99000099
;;; 回文判定のテスト
(are [x y] (= y (palindromic? x))
"abc" false
"aba" true
"aaba" false
"aabaa" true
"a" true
"" true)
;;; nseqのテスト
(is (= (nseq 1) (range 1 10)))
(is (= (nseq 2) (range 10 100)))
(is (= (nseq 3) (range 100 1000)))
(ns tnoda.projecteuler.problem-4
(:require [clojure.string :as str])
(:use clojure.test))
(defn- parindromic?
[x]
(let [s (str x)]
(= s (str/reverse s))))
(defn- solver*
[n]
(let [u (apply * (repeat n 10))
l (long (* 9/10 u))]
(apply max (for [a (range l u)
b (range a u)
:let [m (* a b)]
:when (parindromic? m)]
m))))
(def solver (partial solver* 3))
(is (= 9009 (solver* 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment