Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.82 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. ;;
  2. ;; helper methods for euler.clj - trying to learn some clojure
  3. ;; by working through some of the problems in http://www.projecteuler.net
  4. ;;
  5. (ns euler
  6.   (:use clojure.contrib.math))
  7.  
  8. ;; Fibonacci value calculation - using tail recursion!
  9. ;; used in: prob-2.
  10. ;; TODO: simplify using (loop ..)
  11. (defn fib
  12.   "return the fibonacci value for a given number"
  13.   ([nn] (fib nn 0 1))
  14.   ([nn cur nxt]
  15.    (if (= nn 0)
  16.      cur
  17.      (recur (- nn 1) nxt (+ cur nxt)))))
  18.  
  19.  
  20. ;; calculate the factorial of a positive integer
  21. (defn fact
  22.   "Factorial of a number"
  23.   ([nn] (fact nn 1))
  24.   ([nn acc]
  25.    (if (zero? nn)
  26.      acc
  27.      (recur (- nn 1) (* acc nn)))))
  28.  
  29. ;; Test if a given number is a prime one
  30. (defn prime?
  31.   "Uses Wilson's theorem to determine if a number is prime. Not too efficient."
  32.   [nn]
  33.   (if (or (= 0 nn) (= 1 nn))
  34.     false
  35.     (if (or (= 2 nn) (= 3 nn))
  36.       true
  37.       (=
  38.         (mod (fact (dec nn)) nn)
  39.         (dec nn)))))
  40.  
  41.  
  42. ;; list of primes up to given nn. Uses the Sieve of Eratosthenes
  43. ;; algorithm.
  44. (defn primes
  45.   "return a list of all prime numbers up to given value"
  46.   [nn]
  47.   (loop [i 0 lst (range 2 nn)]
  48.     (let [value (nth lst i)
  49.           multiple? #(and (not= % value) (= 0 (mod % value)))]
  50.       (if (or (>= value nn) (= value (last lst)))
  51.         lst
  52.         (recur (+ i 1) (filter #(not (multiple? %)) lst))))))
  53.  
  54. ;; get the max prime factor for a given number
  55. (defn max-prime
  56.   "Given a number nn, determine the largest prime factor"
  57.   [nn]
  58.   ;; the list of primes is sorted in ascending order -
  59.   ;; start from the end (max value) and check to see
  60.   ;; if it divides by the given number. If not, proceed
  61.   ;; to the next largest.
  62.   (loop [values (primes (ceil (sqrt nn)))]
  63.     (let [tail (last values)]
  64.       (do ;;(println values) (println tail)
  65.         (if (= 0 (mod nn tail))
  66.           tail
  67.           (recur (drop-last values)))))))