1 / 7 · Basic
What an algorithm is
The method for finding the greatest common divisor in Book VII of Euclid's Elements, written about 2,300 years ago, still runs in computers today.
Jump to the 10 practice questionsYou will learn
- Say what makes a list of steps an algorithm
- Follow Euclid's algorithm step by step
- Compare two methods by counting steps
1Explain
Three divisions instead of hundreds
Suppose you need the largest number that divides both 1071 and 462. You could try every number from 462 down to 1 and stop at the first one that divides both. That works, but it may take hundreds of tries. There is a shorter way. Divide 1071 by 462 and keep the remainder, 147.
Watch a and b: each round the pair becomes (b, remainder). When b reaches 0, the answer is in a.
function gcd(a, b) {while (b !== 0) {const r = a % b; // remaindera = b;b = r;}return a;}console.log(gcd(1071, 462)); // 21
21
2Problem
Count the divisions
How many divisions does Euclid's algorithm need for 1071 and 462?
Hint
1071 % 462, then 462 % 147, then 147 % 21.
Solution
Answer: 3
Each division replaces the pair by (divisor, remainder), and the pair stops changing when the remainder is 0. 1071 % 462 = 147, 462 % 147 = 21, 147 % 21 = 0. Three divisions.
3Problem
Your turn: 48 and 18
Using Euclid's algorithm, what is the greatest common divisor of 48 and 18?
Hint
48 % 18 = 12, then 18 % 12 = 6, then 12 % 6 = 0.
Solution
Answer: 6
Euclid’s method replaces the pair (a, b) with (b, a % b), because a common divisor of a and b also divides the remainder. 48 % 18 = 12, 18 % 12 = 6, 12 % 6 = 0. The last non-zero remainder is 6.
4Explain
What an algorithm is
That shorter way is an algorithm: a finite list of precise steps that takes some input and produces the right output. This one is Euclid's algorithm for the greatest common divisor, and it appears in Book VII of the Elements, written around 300 BC. Euclid described it with repeated subtraction of lengths rather than division, but the idea is the same, and the version with remainders is what programs use today.
Three things must hold: every step is precise, the steps stop after a finite number of rounds, and the output is right for every allowed input.
5Problem
Not a requirement
Which of these is not a property every algorithm must have?
Hint
Euclid wrote his method down more than 2,000 years ago.
Solution
Answer: It uses a computer
Euclid's algorithm is more than 2,000 years older than computers. An algorithm can be carried out by a person with a pencil.
6Problem
Why it stops
Why does Euclid's algorithm always stop?
Hint
Compare each remainder with the divisor before it.
Solution
Answer: The remainder is always smaller than the divisor, so it shrinks to 0
Each remainder is a smaller whole number than the one before it, and whole numbers cannot keep shrinking forever.
7Explore
Same problem, two speeds
One problem usually has many correct algorithms, and they can differ enormously in how much work they do. For the greatest common divisor of 1071 and 462, trying every number from 462 downward needs 442 tries before it reaches 21, while Euclid's method needs 3 divisions. Both are correct. Only one is quick. Much of this course is about that second question: once a method is correct, how many steps does it take, and how does that number grow when the input gets bigger?
Trying every number from b downward would need up to b tries. Euclid needs only a handful of divisions, even for 89 and 55, the worst pair below 100.
let a = 1071, b = 462, divisions = 0;
while (b !== 0) {
const r = a % b;
a = b;
b = r;
divisions++;
}
console.log(a); // greatest common divisor
console.log(divisions); // how many divisions21
38Explore
Counting steps on a row of bars
To answer it, computer scientists count basic steps (a comparison, a swap, a division) rather than seconds. Seconds depend on the machine. A count of steps depends only on the algorithm and the input, so it lets you compare two methods fairly. The lab below counts comparisons for you while it sorts a row of bars. Try the same starting order with two different methods and watch the counters.
Selection sort on [5, 1, 4, 2, 8]. Step through and watch the comparison counter: it ends at 10.
9Explore
The same list, another method
Insertion sort gets the same sorted list with 7 comparisons. Both are correct; the counts differ.
10Problem
Steps, not seconds
Why do computer scientists count steps instead of timing in seconds?
Hint
Run the same steps on a faster computer.
Solution
Answer: Seconds depend on the machine; step counts depend only on the algorithm and input
A faster computer runs the same steps in fewer seconds, but the number of steps stays the same, so counts compare methods fairly.
11Explore
Inputs, outputs and edge cases
Before writing an algorithm, write down exactly what goes in and what must come out. For the greatest common divisor: the input is two positive whole numbers, and the output is one whole number that divides both, with no larger number doing the same. That description tells you how to test the result, and it often hints at the steps.
Edge cases still give the right answer: when b is 0 the loop never runs, and a is returned.
function gcd(a, b) {
while (b !== 0) {
const r = a % b;
a = b;
b = r;
}
return a;
}
console.log(gcd(35, 0));3512Problem
gcd(35, 0)
What does gcd(35, 0) return with the loop in this unit?
Hint
Does the loop body run even once?
Solution
Answer: 35
b is already 0, so the loop body never runs and a = 35 is returned. 35 divides both 35 and 0.
13Problem
Five examples
A method gives the right answer for the five examples you tried. Is it correct?
Hint
One counterexample is enough to show a method is wrong.
Solution
Answer: Not necessarily: it must be right for every allowed input
Examples can show a method is wrong, but they cannot show it is right for all inputs. That needs an argument, like the shrinking remainder.
14Problem
Euclid in order
For an initial pair with b greater than 0, put these steps of Euclid's algorithm in order.
- Return a
- Divide a by b and keep the remainder r
- Repeat while b is not 0
- Replace a with b and b with r
Hint
The answer is read off at the very end.
Solution
Answer:
- Divide a by b and keep the remainder r
- Replace a with b and b with r
- Repeat while b is not 0
- Return a
Divide, shift the numbers, repeat until the remainder is 0, then the answer is in a.
15Practice
Finish Euclid
Finish Euclid's algorithm inside gcd. The program should print 6 and then 21.
6
21function gcd(a, b) {
// While b is not 0:
// r = a % b, then a = b, then b = r
return a;
}
console.log(gcd(48, 18));
console.log(gcd(1071, 462));
Hint
Order matters: copy b into a before b is overwritten with r.
A solution
function gcd(a, b) {
while (b !== 0) {
const r = a % b;
a = b;
b = r;
}
return a;
}
console.log(gcd(48, 18));
console.log(gcd(1071, 462));16Practice
Keep the best so far
Write a loop that keeps the largest value seen so far, so the program prints 91. This "keep the best so far" pattern returns in selection sort.
91const prices = [12, 91, 7, 45, 3];
let best = prices[0];
// Go through the list and keep the largest value in best.
console.log(best);
Hint
Replace best only when the new value is bigger.
A solution
const prices = [12, 91, 7, 45, 3];
let best = prices[0];
for (const p of prices) {
if (p > best) best = p;
}
console.log(best);17Explain
Common mistakes
const prices = [12, 91, 7];
const best = prices[0];
for (const p of prices) {
if (p > best) best = p;
}
console.log(best);TypeError: Assignment to constant variable. (line 4)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
A running best changes, so declare it with let, not const.
const prices = [-5, -2, -9];
let best = 0;
for (const p of prices) {
if (p > best) best = p;
}
console.log(best);0const prices = [-5, -2, -9];
let best = prices[0];
for (const p of prices) {
if (p > best) best = p;
}
console.log(best);-2Starting best at 0 fails when every value is negative: 0 is not in the list. Start from the first value instead.
18
Summary
- An algorithm is a finite list of precise steps from input to correct output.
- Euclid's algorithm finds a greatest common divisor by repeated remainders.
- One problem can have many correct algorithms with very different step counts.
- Write down the input, the output and the edge cases before the steps.
- The word comes from al-Khwarizmi's Latin name.