[SOLVED] CS (define (factorial n)

$25

File Name: CS_(define_(factorial_n).zip
File Size: 226.08 KB

5/5 - (1 vote)

(define (factorial n)
(if (= n 1) 1
(* n (factorial (- n 1)))))

(factorial 5)

;substitution model (recursive process)
;(factorial 5)
;(* 5 (factorial (- 5 1)))
;(* 5 (factorial 4))
;(* 5 (* 4 (factorial 3)))
;(* 5 (* 4 (* 3 (factorial 2))))
;(* 5 (* 4 (* 3 (* 2 (factorial 1)))))
;(* 5 (* 4 (* 3 (* 2 1))))
;(* 5 (* 4 (* 3 2)))
;(* 5 (* 4 6))
;(* 5 24)
;120

(define (factorial2 n)
(define (fac-it counter total)
(if (> counter n)
total
(fac-it (+ counter 1)(* total counter))))
(fac-it 1 1))

;substitution model (iterative process)
;(factorial2 5)
;(fac-it 1 1)
;(fac-it (+ 1 1)(* 1 1))
;(fac-it 2 1)
;(fac-it (+ 2 1)(* 1 2))
;(fac-it 3 2)
;(fac-it (+ 3 1)(* 2 3))
;(fac-it 4 6)
;(fac-it (+ 4 1)(* 6 4))
;(fac-it 5 24)
;(fac-it (+ 5 1)(* 24 5))
;(fac-it 6 120)
;120

;(factorial2 5)
;(fac-it 1 1)
;(fac-it 2 1)
;(fac-it 3 2)
;(fac-it 4 6)
;(fac-it 5 24)
;(fac-it 6 120)
;120

(define (recursion)
(+ 1 (recursion)))

(define (iterative x)
(iterative (+ x 1)))

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[SOLVED] CS (define (factorial n)
$25