Blame


1 12687dd9 2023-08-04 jrmu ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 12687dd9 2023-08-04 jrmu ;; about the language level of this file in a form that our tools can easily process.
3 12687dd9 2023-08-04 jrmu #reader(lib "htdp-advanced-reader.ss" "lang")((modname |31.3|) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp") (lib "gui.ss" "teachpack" "htdp")))))
4 12687dd9 2023-08-04 jrmu ;!-1 : N -> number
5 12687dd9 2023-08-04 jrmu ;Computes the factorial of n using structural recursion.
6 12687dd9 2023-08-04 jrmu
7 12687dd9 2023-08-04 jrmu (define (!-1 n)
8 12687dd9 2023-08-04 jrmu (cond
9 12687dd9 2023-08-04 jrmu [(zero? n) 1]
10 12687dd9 2023-08-04 jrmu [else (* n (!-2 (sub1 n)))]))
11 12687dd9 2023-08-04 jrmu
12 12687dd9 2023-08-04 jrmu ;!-2 : N -> number
13 12687dd9 2023-08-04 jrmu ;Computes the factorial of n using an accumulator.
14 12687dd9 2023-08-04 jrmu
15 12687dd9 2023-08-04 jrmu (define (!-2 n)
16 12687dd9 2023-08-04 jrmu (local ;the accumulator represents the product of the natural numbers from (x,n]
17 12687dd9 2023-08-04 jrmu ((define (!-aux x accumulator)
18 12687dd9 2023-08-04 jrmu (cond
19 12687dd9 2023-08-04 jrmu [(zero? x) accumulator]
20 12687dd9 2023-08-04 jrmu [else (!-aux (sub1 x) (* x accumulator))])))
21 12687dd9 2023-08-04 jrmu (!-aux n 1)))
22 12687dd9 2023-08-04 jrmu
23 12687dd9 2023-08-04 jrmu
24 12687dd9 2023-08-04 jrmu ;check-time : N N (N -> N) -> true
25 12687dd9 2023-08-04 jrmu ;To evaluate (f x) t number of times.
26 12687dd9 2023-08-04 jrmu
27 12687dd9 2023-08-04 jrmu (define (check-time t x f)
28 12687dd9 2023-08-04 jrmu (cond
29 12687dd9 2023-08-04 jrmu [(= t 1) (f x)]
30 12687dd9 2023-08-04 jrmu [else (check-time (sub1 t) x f))]))
31 12687dd9 2023-08-04 jrmu
32 12687dd9 2023-08-04 jrmu ;(time (check-time 1000 10000 !-1))
33 12687dd9 2023-08-04 jrmu ;(time (check-time 1000 10000 !-2))
34 12687dd9 2023-08-04 jrmu
35 12687dd9 2023-08-04 jrmu cpu time: 191024 real time: 192079 gc time: 26418
36 12687dd9 2023-08-04 jrmu cpu time: 194636 real time: 195881 gc time: 26174