Created
April 17, 2018 22:06
-
-
Save codigoisaac/7c11f650d41af8e3f6bed26310cae523 to your computer and use it in GitHub Desktop.
A Lisp program for computing the Factorial of any given number in Linear Recursive or in Linear Iterative Process. Try both and notice the difference.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
;;;;Linear Recursion and Iteration | |
;;;Linear Recursive process for computing factorials (fact-r n) | |
(define (fact-r n) | |
(if (= n 1) | |
1 | |
(* n (fact-r (- n 1))))) | |
;;;Linear Iterative process for computing factorials (fact-i n) | |
(define (fact-i n) | |
(factorial-iterative 1 1 n)) | |
(define (factorial-iterative product counter n) | |
(if (> counter n) | |
product | |
(factorial-iterative (* counter product) | |
(+ counter 1) | |
n))) | |
;Try using both process to get the factorial of large numbers as 999999; | |
;The program runs out of memory with (fact-r) but never with (fact-i), | |
;because with the Iterative process only 3 variables are being hold by the system, | |
;while in the Recursive process all the results of all the factorial calculations is being kept in memory. | |
;;In general, an iterative process is one whose state can be summarized by a fixed number of state variables, | |
;;together with a fixed rule that describes how the state variables should be updated as the process moves from state to state | |
;;and an (optional) end test that specifies conditions under which the process should terminate. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment