Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

CORRECTNESS OF EUCLID’S

ALGORITHM
• After step E1, we have m = qn + r, for some integer q. If r = 0, then m is a multiple of
n, and clearly in such a case n is the GCD of m and n. If r !=0, note that any number
that divides both m and n must divide m – qn = r, and any number that divides both n
and r must divide qn + r = m; so the set of divisors of {m,n} is the same as the set of
divisors of {n,r}. In particular, the GCD of {m,n} is the same as the GCD of {n,r}.
Therefore, E3 does not change the answer to the original problem. [Knuth1]

Design and Analysis of Algorithms - Chapter 1 11


ALGORITHM DESIGN TECHNIQUES
• Euclid’s algorithm is an example of a “Decrease and Conquer”
algorithm: it works by replacing its instance by a simpler one (in
step E3)
• It can be shown (exercise 5.6b) that the instance size, when
measured by the second parameter, n, is always reduced by at least
a factor of 2 after two successive iterations of Euclid’s algorithm
• In Euclid’s original, the remainder m mod n is computed by
repeated subtraction of n from m
• Step E0 is not necessary for correctness; it improves time
efficiency

Design and Analysis of Algorithms - Chapter 1 12


NOTION OF ALGORITHM
problem

algorithm

input “computer” output

Algorithmic solution
Design and Analysis of Algorithms - Chapter 1 13
EXAMPLE OF
COMPUTATIONAL PROBLEM:
SORTING
• Statement of problem:
• Input: A sequence of n numbers <a1, a2, …, an>

• Output: A reordering of the input sequence <a´1, a´2, …, a´n> so that


a´i ≤ a´j whenever i < j

• Instance: The sequence <5, 3, 2, 8, 3>

• Algorithms:
• Selection sort
• Insertion sort
• Merge sort
• (many others)
Design and Analysis of Algorithms - Chapter 1 14
SELECTION SORT

• Input: array a[1],…,a[n]


• Output: array a sorted in non-decreasing order
• Algorithm:
• for i=1 to n
swap a[i] with smallest of a[i+1],…a[n]

• see also pseudocode, section 3.1

Design and Analysis of Algorithms - Chapter 1 15

You might also like