Project Euler Problem 29

Problem 29 was trivial. It asks us for the number of distinct values generated by the expression a^b, where a and b are between 2 and 100, inclusive.

Clojure makes this problem a snap by providing us with the set abstraction:

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

(defn euler-29 []
(count (into #{} (for [a (range 2 101)
b (range 2 101)]
(expt a b)))))

(euler-29)

Over on clojure-euler, people seemed to favor the distinct function to using into #{}. I hadn’t ever seen the distinct function before, but I would agree it would be a better choice.

If you don’t mind the decrease in readability, this problem can even be solved by a one-liner:

(count (distinct (for [a (range 2 101) b (range 2 101)] (.pow (bigint a) b))))

See you tomorrow!