lecture14

lecture14 - COMP 250 Winter 2010 14 - recurrences 1 Feb 8,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: COMP 250 Winter 2010 14 - recurrences 1 Feb 8, 2010 Recurrences For algorithms that involve for loops, it is straightforward to write the number of operation t ( n ) as a polynomial, whose the degree depends on the number of nested loops. For example, if we have k nested for loops, each of which run n times, then these loops take time t ( n ) proportional to n k . For recursive algorithms, it is sometimes less obvious how to express t ( n ), and some work needs to be done. Today, we will look at a number of examples. Example 1: Factorial Let t ( n ) be the time it takes to compute n ! . You should have an intuition that t ( n ) is O ( n ). This is easy to see if you use an iterative algorithm to compute n ! since we have a for loop which we iterate n times. What about if we use a recursive algorithm? Algorithm: Factorial(n) if n > then return n * Factorial ( n- 1) end if The recursive algorithm for computing n ! involves a method call and return and a multiplication. These operations can each be done in constant time. Moreover, each method call reduces the problem from size n to size n- 1. This suggests a relationship: t ( n ) = c + t ( n- 1) namely the time it takes to compute n ! is some constant plus the time it takes to compute ( n-...
View Full Document

This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.

Page1 / 3

lecture14 - COMP 250 Winter 2010 14 - recurrences 1 Feb 8,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online