;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname week7_w_full) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ; Fibonacci sequence: ; Fn = Fn-1 + Fn-2 ; F0 = 1 ; F1 = 1 ; First ten terms: 1 1 2 3 5 8 13 21 34 55 ; Has tons of applications, e.g.: limit of Fn / Fn-1 is the "golden ratio" used ; in art and architecture ; Neat! ; fib: number -> number ; returns the nth Fibonacci number (define (fib n) (cond [(= n 0) 1] [(= n 1) 1] [else (+ (fib (- n 1)) (fib (- n 2)))])) (check-expect (fib 3) 3) (check-expect (fib 9) 55) ; how many fib calls do we make ; F0 - 1 ; F1 - 1 ; F2 - 3 (original plus two more) ; F3 - 5 (original plus F2 plus F1) ; F4 - 9 ; F5 - 15 ; F6 - 25 ; # of calls increasing by 50%+ each time ; (* n (fib (- n 2))) (define (fib-fast n) (cond [(= n 0) 1] [(= n 1) 1] [else (local [(define fnminus2 (fib-fast (- n 2)))] (+ (fib-fast-with-prev (- n 1) fnminus2) fnminus2))])) (define (fib-fast-with-prev n prev) (cond [(= n 0) 1] [(= n 1) 1] [else (+ (fib-fast (- n 2)) prev)])) (time (fib-fast 30)) (time (fib-fast 31)) (time (fib-fast 32)) (time (fib-fast 33))