415 lecture note #3
Example: Find the maximum of three numbers, a, b, and c
Example: Algorithm max which finds the maximum of three numbers, a, b, and c.
Input: Three numbers a, b, c
Output: A number which is the largest of the tree input numbers
procedure max(a, b, c) 1. x := a // x is a local/temporary variable 2. if b > x then 3. x := b // update x 4. if c > x then 5. x := c // update x 6. return x
Input: A list of integers s = {s1,..,sn},
and the length n of the list
Output: A number which is the largest in s.
Input: n (an integer), and d (a positive
integer)
Output: q and r (integers)
procedure Div(n, d, q, r)
Input: A positive integer m
Output: true if m is even; false if m
is odd
Example: gcd(30, 105) = 15
| divisor of 30 | |
| divisor of 105 | |
| common |
Examples: 15 | 30, and the quotient is 2.
Let m, n and c be integers.
First, let's check some cases:
Proof:
Let C1 be the set of common divisors of a and b, and C2 be the set of common divisors of b and r. We show C1 Ê C2, and C2 Ê C1. Then we can conclude C1 º C2.
1) Show C1 Ê
C2
Let c Î
C1 be a common divisor of a and b, that is, c | a and c |
b.
From the third property of divisors, we get that c | bq.
Then from the second property of divisors, we get that c | (a - bq) =
r. ... (A)
From (A) and hypothesis, we have that c | b and c | r. Therefore, c is
a common divisor of b and r, that is, c Î
C2.
2) Show C2 Ê
C1
Let c Î
C2 be a common divisor of b and r, that is, c | b and c |
r.
From the third property of divisors, we get that c | bq.
Then from the first property of divisors, we get that c | ( bq + r)
=a. ... (B)
From (B) and hypotehsis, c | a and c | b. Therefore, c is a common
divisor of a and b, that is, c Î
C1.
From 1) and 2), we showed that all common divisor of a and b are also common divisors of b and r. In particular, this is true for the greatest common divisor, i.e., gcd(a, b) = gcd(b, r).
Algorithm
procedure gcd(a, b) 1. if a < b, then 2. swap(a, b) // make a the larger of the two 3. while b != 0 do 4. begin 5. r := a mod b 6. a := b 7. b := r 8. end 9. return a
| iteration | a | b | r | |
| 1 | gcd(105, 30) | 105 | 30 | 15 |
| 2 | ||||
| 3 |
| iteration | a | b | r | |
| 1 | ||||
| 2 | ||||
| 3 |