Just going to post my code in this thread, it will be uncommented until I start getting into the harder problems.
My lisp code is under SBCL. My haskell code is using Haskell Platform 2011.4.0.0
If someone wants to post there own feel free, if you've never tried Project Euler before and get as bored around the holidays as I do then I'd recommend trying it.
Problem 1
(defun prob1 ()
(let ((x 0)
(total 0))
(loop (setq total (+ total
(cond
((or (= 0 (mod x 3)) (= 0 (mod x 5))) x)
(t 0))))
(when (= x 999)
(return total))
(incf x))))
(defun newprob1 (x)
(cond
((= x 1000) 0)
((or (= 0 (mod x 3)) (= 0 (mod x 5))) (+ x (newprob1 (incf x))))
(t (+ 0 (newprob1 (incf x))))))
sum [x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]
Problem 2
(defun fib(x)
(if (or (= x 1) (= x 2))
1
(+ (fib (1- x)) (fib (- x 2)))))
(defun prob2 (x)
(let ((f (fib x)))
(if (> f 4000000)
0
(if (evenp f)
(+ f (prob2 (1+ x)))
(prob2 (1+ x))))))
prob2 a b [] = prob2 a b [a, b]
prob2 a b lst = if ((a + b) < 4000000)
then prob2 b (a + b) (filter even lst ++ [(a + b)])
else sum lst
Problem 3
(defun prob3(num &optional (x 2))
(if (= num x)
(print x)
(if (= (mod num x) 0)
(progn
(print x)
(prob3 (/ num x)))
(prob3 num (1+ x)))))
Problem 4
(defun palindrome?(num)
(= num (read-from-string (reverse (write-to-string num)))))
(defun prob4(a b &optional (largest 0))
(if (and (= a 999) (or (= b 999) (> b 999)))
(print largest)
(if (and (< a 999) (= b 1000))
(prob4 (1+ a) 100 largest)
(if (and (palindrome? (* a b)) (> (* a b) largest))
(prob4 a (1+ b) (* a b))
(prob4 a (1+ b) largest)))))
Problem 5
(defun mod2to20?(num &optional (x 2))
(if (= x 21)
t
(if (= 0 (mod num x))
(mod2to20? num (1+ x))
nil)))
(defun prob5(num)
(if (mod2to20? num)
(print num)
(prob5 (1+ num))))
Problem 6
(defun sum-of-squares(begin end)
(if (> begin end)
0
(+ (* begin begin) (sum-of-squares (+ 1 begin) end))))
(defun square(x)
(* x x))
(defun square-of-sum(begin end)
(let ((total 0))
(loop
(when (> begin end)
(return (square total)))
(setq total (+ total begin))
(incf begin))))
(defun prob6(begin end)
(- (square-of-sum begin end) (sum-of-squares begin end)))
(defun newprob6(begin end)
(loop for i from begin to end
sum i into nums
sum (* i i) into squares
finally (return (- (* nums nums) squares))))


Sign In
Create Account


Back to top









