lecture916

4
CHAPTER 2 Mathematics for Algorithms

Upload: munkhchimeg

Post on 10-Jun-2015

181 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Lecture916

CHAPTER 2

Mathematics for Algorithms

Page 2: Lecture916

Example 2.2.6 Factorial

This algorithm computes the factorial of n.

factorial(n) {i = 1

fact = 1while (i < n) {

i = i + 1 fact = fact * i } return fact}

Page 3: Lecture916

Example 2.3.1 Finding the Maximum Value in an Array Using a While LoopThis algorithm finds the largest number in the array s[1], s[2], ... , s[n].

Input Parameter: sOutput Parameters: Nonearray_max_ver1(s) {

large = s[1] i = 2 while (i ≤ s.last) { if (s[i] > large) // larger value found large = s[i] i = i + 1 } return large}

Page 4: Lecture916

Example 2.4.3

example(n) {if (n == 1)

returnfor i = 1 to n

x = x + 1example(n/2)

}