The second project Euler problem is:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Brute force Fibonacci generator:

(define fibo
  (lambda (n)
    (cond
      ((= n 1)
       1)
      ((= n 2)
       2)
      (else (+ (fibo (- n 1)) (fibo (- n 2)))))))

But that takes exponential time, and the problem requires generating all of the numbers anyway, so we can use something like:

(define fibo-sum
  (lambda (a b lim)
    (let* ((c (+ a b)))
      (cond
        ((< lim c) 0)
        (else (+ c (fibo-sum b c lim)))))))

to get the sum of all the fibonacci numbers less than lim (use (fibo-sum 1 2 4000000)). I could add a test for even numbers to solve the problem, but more elegantly we notice that the pattern of the fibonacci numbers has to be odd-odd-even-odd-odd-even, so we have:

(define euler2
  (lambda (a b lim)
    (let* ((c (+ a b))
           (d (+ b c))
           (e (+ c d)))
      (cond
        ((< lim e) 0)
        (else (+ e (euler2 d e lim)))))))
(euler2 1 0 4000000)

We start the fibonacci sequence with 1 0 so that the 2 is part of our sum. And we get the correct answer, 4613732, imperceptibly fast.

One bug that took me forever to find was a mistyped line:

(let* ((c (+ a b))
  (d (+ b c))
   (e (+ d e)))

Where e was defined in terms of d and e, so it used the global value of e. If it hadn't been defined, it would have given me an error immediately, but unfortunately, DrScheme has it pre-defined as #i2.718281828459045 so my code went happily along giving me the wrong answers.

Leave a Reply


Warning: Undefined variable $user_ID in /home/public/blog/wp-content/themes/evanescence/comments.php on line 75