
Untitled
By: a guest on
May 2nd, 2012 | syntax:
None | size: 1.82 KB | hits: 15 | expires: Never
;;
;; helper methods for euler.clj - trying to learn some clojure
;; by working through some of the problems in http://www.projecteuler.net
;;
(ns euler
(:use clojure.contrib.math))
;; Fibonacci value calculation - using tail recursion!
;; used in: prob-2.
;; TODO: simplify using (loop ..)
(defn fib
"return the fibonacci value for a given number"
([nn] (fib nn 0 1))
([nn cur nxt]
(if (= nn 0)
cur
(recur (- nn 1) nxt (+ cur nxt)))))
;; calculate the factorial of a positive integer
(defn fact
"Factorial of a number"
([nn] (fact nn 1))
([nn acc]
(if (zero? nn)
acc
(recur (- nn 1) (* acc nn)))))
;; Test if a given number is a prime one
(defn prime?
"Uses Wilson's theorem to determine if a number is prime. Not too efficient."
[nn]
(if (or (= 0 nn) (= 1 nn))
false
(if (or (= 2 nn) (= 3 nn))
true
(=
(mod (fact (dec nn)) nn)
(dec nn)))))
;; list of primes up to given nn. Uses the Sieve of Eratosthenes
;; algorithm.
(defn primes
"return a list of all prime numbers up to given value"
[nn]
(loop [i 0 lst (range 2 nn)]
(let [value (nth lst i)
multiple? #(and (not= % value) (= 0 (mod % value)))]
(if (or (>= value nn) (= value (last lst)))
lst
(recur (+ i 1) (filter #(not (multiple? %)) lst))))))
;; get the max prime factor for a given number
(defn max-prime
"Given a number nn, determine the largest prime factor"
[nn]
;; the list of primes is sorted in ascending order -
;; start from the end (max value) and check to see
;; if it divides by the given number. If not, proceed
;; to the next largest.
(loop [values (primes (ceil (sqrt nn)))]
(let [tail (last values)]
(do ;;(println values) (println tail)
(if (= 0 (mod nn tail))
tail
(recur (drop-last values)))))))