Skip to content

Instantly share code, notes, and snippets.

@simlun

simlun/euler.clj

Created Jul 7, 2012
Embed
What would you like to do?
euler002
(ns euler002.euler)
(defn- fib-fast
[i a b limit]
(if
(< i limit)
(fib-fast (inc i) b (+ a b) limit)
b))
(defn fib
[n]
(if
(= n 0)
0
(fib-fast (bigint 1) (bigint 0) (bigint 1) (bigint n))))
(defn- even-fibs-less-than
[max-fib]
(for [n (range)
:let [f (fib n)]
:when (even? f)
:while (< f max-fib)]
f))
(defn sum-even-fibs-less-than
[max-fib]
(reduce + (even-fibs-less-than max-fib)))
(ns euler002.euler-test
(:use midje.sweet
euler002.euler))
(fact
(fib 0) => 0
(fib 1) => 1
(fib 2) => 1
(fib 3) => 2
(fib 4) => 3
(fib 12) => 144)
(fact "fib can handle even bigint-large numbers, just for fun"
(fib 92) => 7540113804746346429
(fib 93) => 12200160415121876738)
(fact "The Project Euler problem 2 answer"
(sum-even-fibs-less-than 4000000) => 4613732)
@simlun

This comment has been minimized.

Copy link
Owner Author

@simlun simlun commented Jul 7, 2012

Cred till @petterik för fib-fast ;D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment