40 likes | 56 Views
CHAPTER 2. Mathematics for Algorithms. Example 2.2.6 Factorial. This algorithm computes the factorial of n. factorial ( n ) { i = 1 fact = 1 while ( i < n ) { i = i + 1 fact = fact * i } return fact }.
E N D
CHAPTER 2 Mathematics for Algorithms
Example 2.2.6 Factorial This algorithm computes the factorial of n. factorial(n) { i = 1 fact = 1 while (i < n) { i = i + 1 fact = fact * i } return fact }
Example 2.3.1 Finding the Maximum Value in an Array Using a While Loop This algorithm finds the largest number in the array s[1], s[2], ... , s[n]. Input Parameter: s Output Parameters: None array_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) return for i = 1 to n x = x + 1 example(n/2) }