Permalink
Browse files

Solved 97.

  • Loading branch information...
1 parent 1e70a0a commit a3c37217377e86898e36b17328d6147fa6ef199f @darrenaustin committed Oct 7, 2011
Showing with 29 additions and 1 deletion.
  1. +0 −1 README.md
  2. +29 −0 src/dma/euler/p097.clj
View
@@ -46,7 +46,6 @@ it in Ruby. Here is my migration TODO list. Problems I have solved
in Ruby, but not yet in Clojure:
* 96
-* 97
* 98
* 99
* 111
View
@@ -0,0 +1,29 @@
+(ns dma.euler.p097
+ (:use dma.euler.numeric))
+
+;; So the tricky part of this problem is doing the power expansion
+;; without allowing the numbers to get prohibitively large. Because
+;; we only need the last 10 digits, we can manually expand the powers
+;; but strip each iteration to only the last 10 digits.
+;;
+;; We abstract the stripping of the last ten digits by passing
+;; in a function to do the stripping to the power function.
+;;
+;; We also optimize this by taking advantage of the fact that:
+;; x ^ n = (x * x) ^ (n / 2) for even n. This dramatically
+;; reduces the number of times through the expansion.
+(defn power [x, n, limit]
+ (cond (= n 0) 1
+ (= n 1) (limit x)
+ (even? n) (recur (limit (* x x)) (/ n 2) limit)
+ :else (limit (* x (power (limit (* x x)) (/ (dec n) 2) limit)))))
+
+;; A helper function that creates a function that will
+;; return only the last n digits of the number
+(defn last-n-digits [n]
+ (let [limit (bigint (Math/pow 10 n))]
+ (fn [x] (rem x limit))))
+
+(defn solution {:answer 8739992577} []
+ (let [last-10 (last-n-digits 10)]
+ (last-10 (inc (* 28433 (power 2 7830457 last-10))))))

0 comments on commit a3c3721

Please sign in to comment.