6.1 About this chapter
6.2 An introduction to algorithms
A description inlcudes:
- A name for the algorithm
- A brief description of the task performed by the algorithm
- A description of the input
- A description of the output
- A sequence of steps to follow
Pseudocode: a language in between written English and a computer language
Assignment: a varaible is given a value
6.3 Greatest common divisor and Euclid’s algorithm
GCD Theorem:
For any positive integers , , .
Proof:
Let , where .
If and , then , so .
Conversely, if and , then , so .
Thus, and have the same common divisors. Therefore, .
Input: two positive integers, and
Output:
If (x < y)
Swap x and y.
r := y mod x.
While (r != 0)
y := x
x := r.
r := y mod x.
End-while
Return (x)
Extendeed Euclidean algorithm:
Finds integers such that .
In each iteration, , where .
The last nonzero remainder is . Use back-substitution to find and .
Multiplicative inverse: such that , exists if and only if
Extended Euclidean Algorithm:
For any integers , there exist integers , .
Proof:
Let , where .
By the GCD Theorem, . Suppose recursively that .
Substituting , we get .
Thus, the coefficients are updated by and .
At the base case , .
Therefore, back-substitution produces integers satisfying .
6.4 Fast exponentiation
Input: positive integers , , and .
Output:
p := 1
s := x
r := y
While (r > 0)
If (r mod 2 = 1)
p := p * s mod n
s = s * s mod n
r = r div 2
End-while
6.5 Loop invariants
NOTE: SLIGHTLY DIFFERENT APPROACH TAUGHT IN CLASS
Program verification: formally proving that programs perform correctly
A program’s correct behavior:
- Precondition is true before program starts
- The program will end after a finite number of steps
- Postcondition is true after the program ends
If the loop condition for a while loop is true, the instructions inside the loop are executed.
Loop invariant: an assertation that is true before each iteration of a loop
Let indicate loop condition and indicate loop invariant. Using a loop invariant:
- The precondition is true before the loop begins, then is also true
- and are both true before an iteration of the loop, then is true after the iteration
- The condition will eventually be false
- Show that if and are both true, then the postcondition is true
Example:
Precondition:
Postcondition:
Loop Invariant: , and is an integer.
Step 1: Initialization
Since and , the invariant is true.
Step 2: Maintenance
After one iteration:
is an integer. Thus, the invariant holds.
Step 3: Termination
increases by 1 each time. When , the loop stops.
Step 4: Correctness
Loop ends: .
Invariant: .
Thus, , so .