TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Learning Clojure with Project Euler

38 pointsby grokcodeover 15 years ago

5 comments

spuzover 15 years ago
The 2nd and 3rd solutions are also incorrect.<p>The second solution will run indefinitely:<p><pre><code> (defn e2 [limit] (filter #(and (&#60; % limit) (zero? (mod % 2))) fibs)) </code></pre> Using a predicate in the filter function of "&#60; limit and mod 2 == 0" does not work as the fibs sequence is evaluated even after the terms in the sequence become greater than the limit (all it means is that every term above the limit is filtered out). Replacing the limit check with <i>take-while</i> would fix this.<p>The third solution is also broken, it works fine for small values of n but enter a large number such as is given in the problem and you quickly run out of stack. Replacing the recursive call with <i>recur</i> will enable tail-call optimisation and give your stack a lot more breathing room.<p>I recommend the clojure-euler wiki for more reliable examples of good clojure code :)
评论 #837456 未加载
alrex021over 15 years ago
wiki for Clojure solutions <a href="http://clojure-euler.wikispaces.com/" rel="nofollow">http://clojure-euler.wikispaces.com/</a><p>nice ;)<p>Actually, on serious note, a great way to compare if your clojure code looks anything like it should.
alrex021over 15 years ago
&#62;The above simply creates a lazy sequence of all of the numbers between (inclusive) 1 and limit - 1.<p>&#62; (range 1 (- limit 1))<p>this is wrong, it should be: (range 1 limit)<p>which will produce: (1 2 3 ... 999)
zckover 15 years ago
This is interesting. I'd be interested to see the runtimes of these programs. It's fascinating to see how fast some of the most seemingly-complicated problems go. (It's also fun to use a programming language with unlimited-size integers, as I think Clojure has -- for an example, see problem 97. Arc just did the arithmetic in 44 milliseconds without me having to do any optimization.)
评论 #838167 未加载
scrameover 15 years ago
Funny, I just started a new repo for doing euler problems with clojure. I'm only on the first couple problems, but am generally pretty impressed. For the seconed problem (sum of fibonaccis), my commit message is this: confirmed, timed at: "Elapsed time: 0.41989 msecs" -- original c solution will no longer run.<p>My old 32 bit machine died and the original (crappy) C solution now segfaults immediately, and was much slower.<p>Anyway, calculating and summing all the fibonacci numbers in less than half a millisecond is pretty cool.