edubun
English
1 / 18

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 questions

You 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.

  1. function gcd(a, b) {
  2. while (b !== 0) {
  3. const r = a % b; // remainder
  4. a = b;
  5. b = r;
  6. }
  7. return a;
  8. }
  9. console.log(gcd(1071, 462)); // 21
Variables
Output
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.

a
b
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 divisions
Output
21
3

8Explore

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.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

9Explore

The same list, another method

Insertion sort gets the same sorted list with 7 comparisons. Both are correct; the counts differ.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

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.

input
function gcd(a, b) {
  while (b !== 0) {
    const r = a % b;
    a = b;
    b = r;
  }
  return a;
}
console.log(gcd(35, 0));
Output
35

12Problem

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.

  1. Return a
  2. Divide a by b and keep the remainder r
  3. Repeat while b is not 0
  4. Replace a with b and b with r
Hint

The answer is read off at the very end.

Solution

Answer:

  1. Divide a by b and keep the remainder r
  2. Replace a with b and b with r
  3. Repeat while b is not 0
  4. 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.

Expected output
6
21
Your code
function 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.

Expected output
91
Your code
const 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);
Error message
TypeError: Assignment to constant variable. (line 4)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. 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.

Mistake
const prices = [-5, -2, -9];
let best = 0;
for (const p of prices) {
  if (p > best) best = p;
}
console.log(best);
Output
0
Fixed
const prices = [-5, -2, -9];
let best = prices[0];
for (const p of prices) {
  if (p > best) best = p;
}
console.log(best);
Output
-2

Starting 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.

Next unitSearching: linear and binary search
Full text · The whole lesson as one text

A method that always works

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. Now divide 462 by 147 and keep the remainder, 21. Divide 147 by 21: the remainder is 0, so the answer is 21. Three divisions instead of several hundred.

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.

function gcd(a, b) {
  while (b !== 0) {
    const r = a % b;   // remainder
    a = b;
    b = r;
  }
  return a;
}
console.log(gcd(1071, 462)); // 21

What makes a list of steps an algorithm

Textbooks such as the one by Cormen, Leiserson, Rivest and Stein describe an algorithm as a well-defined procedure that turns an input into an output. Three things are packed into that description, and each one matters when you write code.

  • Precise. Each step means one thing. "Divide a by b and keep the remainder" is precise; "make the numbers smaller somehow" is not.
  • Finite. It must stop. In Euclid's algorithm the remainder is always smaller than the number you divided by, so it shrinks every round and must reach 0.
  • Correct. For every allowed input, the output is the right answer, not only for the examples you tried.

A cooking recipe is often given as an everyday example, and it is a fair one: ingredients are the input, the dish is the output, and the steps are in order. The difference is how much the reader fills in. A cook decides what "a pinch" means. A computer decides nothing, which is why algorithms for computers are written with every step spelled out.

Same problem, different algorithms

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?

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 and insertion sort on the same eight values. The counters show how many comparisons and swaps each one needs.

Inputs, outputs and the steps between

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. It also reveals the edge cases: what if one number is 0? (The loop above returns the other number, which is the correct answer.) What if the two numbers are equal? Thinking about edge cases before running the code catches many mistakes.

BackgroundThe word algorithm comes from a person's name. Muhammad ibn Musa al-Khwarizmi worked in Baghdad in the ninth century and wrote a book on calculating with the Hindu numerals 0 to 9. Its Latin translation opens with the words "Dixit algorizmi", meaning "al-Khwarizmi said", and is usually called "Algoritmi de numero Indorum". The Latin forms of his name, algorizmi and algoritmi, became the word for a step-by-step method of calculation. His book on solving equations gave us another word: algebra. Much later, in 1843, Ada Lovelace published notes on Charles Babbage's unbuilt Analytical Engine; the last of them, Note G, sets out step by step how the machine could compute Bernoulli numbers.
  • About 300 BC: Euclid's Elements, Book VII: the greatest common divisor method.
  • 9th century: Al-Khwarizmi in Baghdad writes on Hindu numerals; his Latin name gives the word algorithm.
  • 1843: Ada Lovelace's Note G: steps for the Analytical Engine to compute Bernoulli numbers.
  • 1945: John von Neumann proposes merge sort.
  • 1959: Tony Hoare devises quicksort in Moscow (published 1961).
Key points
  • 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.

Practice questions from What an algorithm is on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17