#| Euler #2 in Racket Problem 2 """ 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. """ This Racket program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Racket page: http://www.hakank.org/racket/ |# #lang racket (provide (all-defined-out)) ;; #lang racket/base (require (only-in math fibonacci sum )) ;;; for fibonacci and sum (require (only-in "utils_hakank.rkt" time-function my-fib )) ;;; (require racket/list) ;;; Not needed. #lang racket fast enough. ;;; There's a conflict when using math and racket/list (but not with math and racket). ;;; Both have defined permutation/1 ;;; which I don't use here. ;; (require (only-in math fibonacci sum) ;;; (only-in racket/list range)) ;;; cpu time: 791 real time: 791 gc time: 0 (define (euler2a) (sum (filter (lambda (n) (and (= (modulo n 2) 0) (< n 4000000)) ) (map my-fib (range 1 40))))) ;;; cpu time: 809 real time: 809 gc time: 0 (define (euler2b) ;;; (sum (filter (lambda (n) (and (even? n) (< n 4000000)) ) (map my-fib (range 1 40))))) ;;; cpu time: 0 real time: 0 gc time: 0 (define (euler2c) ;;; (sum (filter (lambda (n) (and (even? n) (< n 4000000)) ) (map fibonacci (range 1 40))))) ;; All the one above are cheating by using a constant range. ;; Use for*/sum and in-naturals instead... ;; This works but way too complex. ;; (define (euler2d) (let ([s 0] [run #t]) (for ([i (in-naturals 1)] #:break (equal? run #f)) (let ( [f (fibonacci i)]) (when (> f 4000000) (set! run #f)) (when (<= f 4000000) (when (even? f) (set! s (+ s f)) ) ) ) ) s)) ;;; cpu time: 0 real time: 0 gc time: 0 (define (euler2e) (for/sum ([i (in-naturals 1)] #:do [(define f (fibonacci i))] #:break (> f 4000000) #:when (even? f)) f) ) (define (run) ;;; (time-function euler2a) ;;; (time-function euler2b) ;;; (time-function euler2c) ;;; (time-function euler2d) (time-function euler2e) ) (run)