lecture916
TRANSCRIPT
CHAPTER 2
Mathematics for Algorithms
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}
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}
Example 2.4.3
example(n) {if (n == 1)
returnfor i = 1 to n
x = x + 1example(n/2)
}