0

Structure and Interpretation of Computer Programs section 1.2.1 Linear Recursion and Iteration:

Compare the two processes... each requires a number of steps proportional to n to compute n!

The two processes are specified by

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

;; This is the linear recursive process
(define (factorial n)
 (define (iter product counter)
   (if (> counter n)
       product
       (iter (* counter product)
             (+ counter 1))))
 (iter 1 1))

;; This is the linear iterative process

My question is: how do both processes require a number of steps proportional to n to compute n! ?

mohamadc
  • 13
  • 1
  • It means that if we want to compute the factorial of `n`, we have to iterate more or less `n` times: `c * n` times, with `c` an arbitrary constant. – Óscar López Aug 05 '19 at 06:23

2 Answers2

0

For the 1st process; you have to do these steps in one recursive loop:

- check if n equals 1
- multiply n with (factorial (- n 1))
  if we split it a little, it includes (- n 1) and a function call and a multiplication.

Let just roughly count these as 4 steps.

And because you have to do these 4 steps until n = 1, totally it is 4*n steps. so it is proportional to n. (let's ignore some details, e.g., processing of n=1 case is a little bit different because when n is large enough, it can be ignored)

The 2nd one is the same

user1461328
  • 742
  • 2
  • 6
  • 13
0

In both cases the procedures will keep running until a certain condition is met.

  • Recursive process will keep invoking the (factorial) procedure and decreasing n until n=1
  • Iterative process will keep increasing the counter variable until counter > n

The larger the value of n the longer it will take to satisfy each termination check.

Example: (factorial 1000) will take longer than (factorial 10) simply because getting 1000 to 1 will take 999 steps reducing n by 1 every time factorial is invoked (in the recursive process). On the other hand, getting 10 to 1 will take you just 9 steps.

Hope that answers your question.

obviyus
  • 134
  • 1
  • 9