Skip to content

Instantly share code, notes, and snippets.

@futureperfect
Created December 8, 2011 08:50
Show Gist options
  • Save futureperfect/1446491 to your computer and use it in GitHub Desktop.
Save futureperfect/1446491 to your computer and use it in GitHub Desktop.
Solutions for Project Euler problems
;(compile-file "euler.lisp")
(defun fib (n)
(if (or (= n 0)
(= n 1))
1
(+ (fib (- n 1))
(fib (- n 2)))))
(defun square (number)
"square an integer"
(* number number))
(defun p1 (number)
"Add all natural numbers below 'number' that are multiples of 3 or 5"
(loop for i from 0 to (- number 1)
when (or (= (mod i 3) 0)
(= (mod i 5) 0))
sum i))
(defun p2 (number)
"find the sum of all even terms of the fibonnaci sequence less than number"
(loop for i from 2
while (<= (fib i) number)
when (evenp (fib i)) sum (fib i)))
(defun p3 (number)
"Find largest prime factor of number"
(loop for i from 2 to (ceiling (sqrt number))
when (= (mod number i) 0)
collect i))
(defun p4 ()
"Find the largest palindrome that is a product of two 3-digit numbers"
(loop for i from 100 to 999
maximize (loop for j from 100 to 999
when (equalp (write-to-string (* i j))
(reverse (write-to-string (* i j))))
maximize (* i j))))
(defun p6 (n)
"difference between sum of squares and square of sums from 1 to n"
(- (square (loop for i from 1 to n
sum i))
(reduce #'+
(mapcar #'square
(loop for i from 1 to n
collect i)))))
(defun divisible-by (number list)
"return true if divisible by an element in the list"
(loop for i in list
thereis (= (mod number i) 0)))
(defun prime-list-generator (current max-value prime-list)
"business end of p10"
(if (= current max-value)
prime-list
(if (divisible-by current prime-list)
(prime-list-generator (+ current 1) max-value prime-list)
(prime-list-generator (+ current 1) max-value (nconc prime-list (list current))))))
(defun p10 (n)
"Find the sum of all the primes below n"
(reduce #'+ (prime-list-generator 2 n '())))
(defun p48 ()
"Find the last 10 digits of 1^1 + 2^2 + 3^3 + ... + n^n"
(mod (loop for x from 1 to 1000 sum (expt x x)) (expt 10 10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment