Euler: Problem 94

Posted by YpsilonTAKAI On 2013年2月12日火曜日 0 コメント
辺の長さと面積が整数になる、「ほぼ正三角形」を見つける問題です。

始めに総当たりで解くやつを作ったら、10時間かかりました。さすがにこれはだめなので、恒例の逆から考えるパターンです。



問題の三角形で、等しい辺の長さをa、残りの辺の長さを2b、高さをhとすると、a,b,hがピタゴラス数になるので、それぞれの辺は、

・パターンA
    


もしくは、

・パターンB
    

と表わすことができます。問題の条件から、  です。 パターンAの場合、



となります。これって、前にやったペルの方程式の形です。この形になったら、最小の1つがわかれば残りは計算でもとめられます。
さて、パターンBの方はどうかというと、



こんな風に、同じ形に持っていくことができます。
後は、 形のペルの方程式の最小解がわかればいいのですが、問題に、a=5、b=3という値が出ているので、これから求めると、(2,1)であることがわかります。

周の長さをx,yで表わすと、パターンAの場合は  、パターンBの場合は、 となります。

これで解いたのが2つめです。
なんと、1msec以下の時間で解けます。

すごい。

;; Problem 94
;; "Elapsed time: 0.308908 msecs"
(require '[clojure.math.numeric-tower :as math])
(defn pell-seq [[x y] n]
(iterate (fn [[a b]] (vector (+ (* a x) (* n b y))
(+ (* a y) (* b x))))
[x y]))
(defn pe-94 [limit]
(+ (reduce + (->> (pell-seq [2 1] 3)
(map (fn [[a b]] (* 4 a a)) ,,)
(take-while #(< % limit) ,,)))
(reduce + (->> (pell-seq [2 1] 3)
(map (fn [[a b]] (* 2 (+ a b b b) (+ a b b b))) ,,)
(take-while #(< % limit) ,,)))))
view raw pe_94.clj hosted with ❤ by GitHub
;; Problem 94
;; toooooo slow!! needs almost 10 hours!!!
;; "Elapsed time: 3.4820469154548E7 msecs"
(require '[clojure.math.numeric-tower :as math])
(defn area-of-isosceles-triangle [leg base]
(* base
(math/sqrt (- (math/expt leg 2)
(math/expt (/ base 2) 2)))
(/ 1 2)))
(defn almost-equilateral-triangle-areas [leg]
[[(area-of-isosceles-triangle leg (dec leg)) (- (* leg 3) 1)]
[(area-of-isosceles-triangle leg (inc leg)) (+ (* leg 3) 1)]])
(defn pe-94 [limit]
(->> (range 2 (/ limit 3))
(mapcat almost-equilateral-triangle-areas ,,)
(filter #(integer? (first %)) ,,)
(map second ,,)
(reduce + ,,)))
(time (pe-94 (math/expt 10 9)))
view raw pe_94_slow.clj hosted with ❤ by GitHub



0 コメント:

コメントを投稿