Lisp Makes Project Euler Easy
Lets review the first 3 problems to support this claim. A few things are common to the answers below. First is that there is no code to deal with representation of numbers in the computer. This is taken care of by the language for arbitrarily large numbers. Second is the use of the map reduce paradigm which removes most of the need to think about how to iterate. Instead, simply map a function to all values and then reduce all of the results.
Problem 1
"Add all the natural numbers below one thousand that are multiples of 3 or 5."
First we create nums-list
which creates a sequential list of natural numbers as large as you want. We then make 3or5
which returns the number if it is divisible by 3 or 5 and otherwise 0. Then we use the magic of mapping and reducing. We map 3or5 to all numbers from 1 to 999 and reduce the list with addition.
Problem 2
"By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
First we create fib
which returns the nth Fibonacci number. We then make evenret
which returns the number if it is even or 0 otherwise. Then we use the magic of mapping and reducing. I used quick guess and check to determine that (fib 33)
is the first fib over 4 million in value. So we map fib
from 0 to 33, map that to evenret
and reduce with addition.
Problem 3
"What is the largest prime factor of the number 600851475143?"
This one is a bit more involved. The basic approach is to generate all primes that could be factors, find the actual factors and finally find the largest. The primes are generated in order and use all previous primes to test if subsequent numbers are primes. Almost all of the code is for generating primes.