Our goal is to be able to:
If time permits, we’ll cover NP-theory and ways to address intractability.
- In other words, we won’t be covering NP-theory or intractability.
Algorithm: Sequence of unambiguous instructions for solving a problem in a finite amount of time.
Why Study Them?:
- Theoretical: They’re the core of computer science.
- Practical: They’ll help you design & analyze algorithms for new problems.
We’ll be going through these in this course.
We’ll be doing lots of graph problems.
And now, some introductory problems.
While following along, note how:
Note on Unambiguity: Be thorough! Even the range of input must be defined.
Problem: Find gcd(m,n), the greatest common divisor of two nonnegative, nonzero integers m and n.
Suppose gcd(60,24). We can figure out the GCD is 12 in our heads, but what about an algorithm to get there?
A naive brute-force approach where we let t = min(m,n), and then:
Euclid’s Algorithm is an efficient solution that is based on the repeated application of the equality:
gcd(m,n) = gcd(n, m \% n)
(Why this equality is true is irrelevant to us, just take it as a given)
Describing the Algorithm in English:
Apply the above equality repeatedly until the second parameter becomes zero. At this point the problem becomes trivial to solve (because gcd(x,0) = x).
Describing the Algorithm in Steps:
Describing the Algorithm in Pseudocode:
// GCD via Euclid's Algoritmwhile n \ne 0 dor \leftarrow m % nm \leftarrow nn \leftarrow rreturn m
Q: Use Euclid’s algorithm to solve gcd(60,24) in three steps.
A: gcd(60,24) = gcd(24,12) = gcd(12,0) = 12
Professor’s Recommendation: It’s better to write pseudocode last.
For this problem, we’re just going to skip ahead to the interesting solution.
Problem: How can you find all prime numbers (up to some given n) with an algorithm?
Key Property: It’s easier to tell if a number isn’t prime
This algorithm finds all prime numbers less than or equal to a given interger n.
Describing the Algorithm in Steps:
Describing the Algorithm in Pseudocode:
// Sieve of Eratosthenes// Input: Integer n >= 2// Output: List of primes that are <= n// Generate listfor p \leftarrow 2 to n do A[p] \leftarrow p// The sieve partfor p \leftarrow 2 to \lfloor\sqrt{n}\rfloor do// if p hasn't been eliminated...if A[p] \ne 0// ... derive all non-primes ...j \leftarrow p \large{*} pwhile j \le n do// ... and eliminate themA[j] \leftarrow 0j \leftarrow j \text{$+$} p
First, we generate this list:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After the first cycle on p=2:
2 3 5 7 9 11 13 15 17 19
Next (and last) cycle on p=3:
2 3 5 7 11 13 17 19
After this, no more cycles are needed for our n.