Project Euler Problem 63

Ivar Thorson bio photo By Ivar Thorson

Problem 63 asks “How many n-digit positive integers exist which are also an nth power?”

Once again, we harness the power of a for loop to solve a problem in a very efficient and concise manner.

(use '[clojure.contrib.math :only (expt)])

(defn euler-63 []
  (count
   (for [n (range 1 10)
         p (range 1 30)
</span>         d [(count (str (expt n p)))]
         :when (= d p)]
     [n p])))

(time (euler-63)) ;; "Elapsed time: 25.113318 msecs"

The curious may find it interesting to spend a few minutes to discover why in the for loop above the loop variables n, p have a upper bounds of 10 and less than 30, respectively.

Ciao.