What this chapter is teaching
An algorithm is a precise, step-by-step procedure to arrive at an answer. This chapter explores how algorithms make computation dramatically faster, moving from digit-by-digit addition to divisor lists, Euclid’s subtraction, and Åryabhaṭa’s division algorithm for GCD.
1What is an Algorithm? (Counting Dots vs. Place-Value Addition)
These days the word ‘algorithm’ pops up everywhere. What exactly is an algorithm? What does it have to do with mathematics?
In early childhood, we first learned addition by counting items explicitly: to add 5 and 7, we draw 5 dots, then draw 7 more dots, and finally count the dots up to 12 to get the answer. Imagine adding large numbers this way — for instance 473 + 695!
Fortunately, human mathematics discovered a much faster way: writing numbers one below the other in the Indian base-ten place-value system, with the rightmost digits aligned, and adding column-by-column from right to left with a carry mechanism.
473
+ 695
-----
8
3 + 5 = 8carry = 0
473 + 695 ----- 687 + 9 = 16
write 6, carry = 1
1 1 473 + 695 ----- 11684 + 6 + 1 = 11
final sum = 1,168
Suppose counting one dot takes 1 second, while adding single-digit columns with carry takes 15 seconds:
| Addition Problem | Counting Dots (1 dot/sec) | Digit-by-Digit Algorithm (15 sec/col) | Efficiency Factor |
|---|---|---|---|
| 33 + 27 (Sum = 60) | 60 seconds (1 minute) | 2 columns × 15s = ~30 seconds | 2× faster |
| 334 + 272 (Sum = 606) | 606 seconds (~10 minutes) | 3 columns × 15s = ~45 seconds | 13× faster |
| 3,347 + 2,729 (Sum = 6,076) | 6,076 seconds (~1 hr 41 min) | 4 columns × 15s = ~1 minute | 100× faster! |
2The Column Addition Algorithm & Proof of Correctness
Here is the formal textbook description of our addition algorithm:
- Step 1: Write the numbers one below the other in the Indian base-ten place-value system so that the digits are aligned from right to left.
- Step 2: Add the rightmost digits:
– If the sum is less than 10, write the sum directly below the two digits. Set carry = 0.
– If the sum is more than (or equal to) 10, write the units digit of the sum directly below the two digits. Set carry = 1. - Step 3: Move to the next column of digits on the left. Add the two digits and current carry:
– If the sum is less than 10, write the sum directly below the two digits. Set carry = 0.
– If the sum is more than (or equal to) 10, write the units digit directly below. Set carry = 1. - Step 4: Repeat Step 3 until there are no more digits on the left.
- Step 5: If the value of carry is 1, write 1 to the left of the bottom row.
Mathematical Proof 1: Place-Value Regrouping Justification
Whenever we provide an algorithm, we also have to justify why it works. Combining dots and counting the sum is how addition is defined. Why does adding individual digits from right to left result in the exact sum of the two numbers?
- Algebraic Place-Value Representation: In base 10, any integer A with digits a_k a_{k-1} … a_0 represents:
A = a_k 10ᵏ + a_{k-1} 10^{k-1} + … + a_1 10^1 + a_0 10^0 Similarly, B = b_k 10ᵏ + b_{k-1} 10^{k-1} + … + b_1 10^1 + b_0 10^0. - Combining Groups: By the associative and commutative laws of addition:
A + B = (a_k + b_k) 10ᵏ + … + (a_1 + b_1) 10^1 + (a_0 + b_0) - Carry Mechanism as Base-Ten Regrouping: At the units place, if (a_0 + b_0) ≥ 10, we can uniquely write (a_0 + b_0) = 10 c_1 + s_0, where s_0 ∈ \{0, 1, …, 9\} is the units digit and c_1 = 1 is the carry of ten.
- Propagating to Higher Powers: Substituting back, the tens term becomes (a_1 + b_1) 10 + 10 c_1 = (a_1 + b_1 + c_1) 10^1. This guarantees that every group of ten formed at power 10^i is precisely added to the next higher power 10^{i+1}. Hence, the algorithm calculates the exact sum. Q.E.D.
In any column, each digit is at most 9, and the incoming carry from the previous column is at most 1.
ext{Maximum Column Sum} = 9 + 9 + 1 = 19 Since 19 = 1 imes 10 + 9, the tens digit is at most 1. Because 19 < 20, the carry can never be 2 or more.
- 1. Justifying addition by units, tens, hundreds: Grouping ensures each power of 10 is accumulated separately. When the sum in any power exceeds 9, the quotient (⌊ ext{sum} / 10 floor = 1) is bundled into the next power of 10.
- 2. Adding Decimal Fractions: To add decimals (e.g. 12.35 + 4.8), we modify Step 1: align the numbers by their decimal point rather than rightmost digits. This preserves place value alignment (tenths under tenths, hundredths under hundredths). Empty places are padded with zeros (4.8 o 4.80).
3Computing the Divisors of a Number & Data Structures
Suppose we want to compute gcd(375, 825). How do we find the divisors of 375? The divisors of a number are just the factors of that number. Clearly, any divisor must lie between 1 and 375. The simplest way is to check each number between 1 and 375 and see if it divides 375.
- 1. Start with an empty list list-of-divisors = [ ].
- 2. For each number j in the sequence 1, 2, 3, …, n:
– if j divides n, add j to the list-of-divisors. - 3. Output list-of-divisors.
Running through an algorithm step-by-step is called executing the algorithm:
- Initially list-of-divisors is empty:
[ ] - 1 divides 18 &implies update to
[1] - 2 divides 18 &implies update to
[1, 2] - 3 divides 18 &implies update to
[1, 2, 3] - 4 does not divide 18 &implies leave unchanged as
[1, 2, 3] - 5 does not divide 18 &implies leave unchanged as
[1, 2, 3] - 6 divides 18 &implies update to
[1, 2, 3, 6] - 7 and 8 do not divide 18 &implies leave unchanged as
[1, 2, 3, 6] - 9 divides 18 &implies update to
[1, 2, 3, 6, 9] - 10, 11, 12, …, 17 do not divide 18 &implies leave unchanged as
[1, 2, 3, 6, 9] - 18 divides 18 &implies update to
[1, 2, 3, 6, 9, 18] - Final Output:
divisors(18) = [1, 2, 3, 6, 9, 18](strictly in increasing order).
divisors(375) = [1, 3, 5, 15, 25, 75, 125, 375](8 divisors)divisors(825) = [1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275, 825](12 divisors)
- divisors(15): Testing j ∈ 1 … 15 &implies [1, 3, 5, 15] (15 checks).
- divisors(135): Testing j ∈ 1 … 135 &implies [1, 3, 5, 9, 15, 27, 45, 135] (135 checks).
- divisors(775): Testing j ∈ 1 … 775 &implies [1, 5, 25, 31, 155, 775] (775 checks).
- How does the amount of work increase as numbers grow?
The number of divisibility checks is exactly equal to n. If n grows by a factor of 10 (e.g. from 2-digit to 3-digit), the workload increases tenfold (O(n) complexity).
Data Structures: Naming Intermediate Quantities
When executing an algorithm, we compute intermediate quantities like list-of-divisors and index j. Naming them and maintaining ordered collections are the foundation of data structures, which allow us to organize information to make algorithms cleaner and more efficient.
4Greatest Common Divisor (GCD) & The First Algorithm
The greatest common divisor (gcd) or highest common factor (hcf) of two numbers is the largest number that appears in both collections of divisors.
- 1. Let divisors-of-m be the list obtained by computing divisors(m).
- 2. Let divisors-of-n be the list obtained by computing divisors(n).
- 3. Start with an empty list common-divisors = [ ].
- 4. For each number x in the list of divisors-of-m:
– If x also appears in the list of divisors-of-n, add x to the list common-divisors. - 5. Report the rightmost element of the list common-divisors as gcd(m, n).
- divisors(375) = [1, 3, 5, 15, 25, 75, 125, 375]
- divisors(825) = [1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275, 825]
- Common divisors found: [1, 3, 5, 15, 25, 75]
- Rightmost (largest) element: 75. Hence, gcd(375, 825) = 75.
What happens when the numbers are large, such as 54,000 and 81,000? Inspecting them visually is impossible!
divisors(54000) — 80 divisors:divisors(81000) — 80 divisors:
common-divisors(54000, 81000) — 64 common divisors:
Because the list of common divisors is arranged in increasing order, the largest common divisor is the rightmost element: 27,000. Therefore, gcd(54000, 81000) = 27,000.
5Three Successive Refinements for GCD
Each successive refinement improves efficiency without changing the mathematical correctness of what is being computed:
- min(6, 12) = 6
- Initially set
most-recent-common-divisor = 1 - k = 2 divides both 6 and 12 &implies Update:
most-recent-common-divisor = 2 - k = 3 divides both 6 and 12 &implies Update:
most-recent-common-divisor = 3 - k = 4 does not divide 6 &implies
most-recent-common-divisorremains 3 - k = 5 does not divide 6 &implies
most-recent-common-divisorremains 3 - k = 6 divides both 6 and 12 &implies Update:
most-recent-common-divisor = 6 - Scan complete. gcd(6, 12) = 6. (Zero list memory used!)
6Euclid’s Subtraction Algorithm & Geometric Tiling
In his book Elements (c. 300 BCE), the Greek mathematician Euclid wrote down an elegant algorithm based on problem reduction: assuming m ≥ n, gcd(m, n) = gcd(n, m − n).
Mathematical Proof 3: Justification for Euclid’s Subtraction Principle
- Forward Direction (d | m and d | n ⇒ d | (m - n)):
Let d be a common divisor of m and n. Then m = ad and n = bd for natural numbers a, b.
Then m - n = ad - bd = (a - b)d. Since (a - b) is an integer, d is also a divisor of m - n. - Converse Direction (d | n and d | (m - n) ⇒ d | m):
If d divides both n and m - n, then n = xd and m - n = yd for natural numbers x, y.
Then n + (m - n) = m = xd + yd = (x + y)d. Since (x + y) is an integer, d also divides m. - Conclusion: Any common divisor of m and n is also a common divisor of n and m - n, and vice versa. Hence their greatest common divisors must be identical: gcd(m, n) = gcd(n, m − n). Q.E.D.
If a measuring tile of length d perfectly tiles segments of length m and n, it must also tile the remainder segment of length m - n:
- 1. If m < n, reverse the numbers and compute gcd(n, m).
- 2. If n = 0, report the answer as m.
- 3. Otherwise, reduce the problem to compute gcd(n, m - n).
- Since 375 < 825, Step 1: reverse &implies compute gcd(825, 375).
- Since 825 - 375 = 450, Step 3: reduce &implies compute gcd(375, 450).
- Since 375 < 450, Step 1: reverse &implies compute gcd(450, 375).
- Step 3 (450 - 375 = 75): reduce &implies compute gcd(375, 75).
- Step 3 (375 - 75 = 300): reduce &implies compute gcd(75, 300).
- Since 75 < 300, Step 1: reverse &implies compute gcd(300, 75).
- Step 3 (300 - 75 = 225): reduce &implies compute gcd(75, 225).
- Since 75 < 225, Step 1: reverse &implies compute gcd(225, 75).
- Step 3 (225 - 75 = 150): reduce &implies compute gcd(75, 150).
- Since 75 < 150, Step 1: reverse &implies compute gcd(150, 75).
- Step 3 (150 - 75 = 75): reduce &implies compute gcd(75, 75).
- Step 3 (75 - 75 = 0): reduce &implies compute gcd(75, 0).
- Since n = 0, Step 2 reports the final answer: 75. (7 reductions total).
In general, for any odd number 2k + 1, gcd(2k + 1, 2) requires k subtractions! The number of steps is proportional to the numerical value, not the number of digits.
7Åryabhaṭa’s Division Algorithm (Repeated Division by Remainder)
In Indian mathematical treatises, notably Åryabhaṭa’s Åryabhaṭīya (499 CE), we see the “long division” method for finding GCD using Indian place-value numerals. It makes efficient use of repeated “division by remainder” in place of repeated subtraction.
When one starts with 99 and subtracts 2 repeatedly, what remains once one cannot subtract 2 anymore is precisely the remainder when 99 is divided by 2 (i.e. 99 mod 2 = 1).
- 1. If m < n, reverse the numbers and compute gcd(n, m).
- 2. If n = 0, report the answer as m.
- 3. Otherwise, reduce the problem to computing gcd(n, m mod n).
- Step 3 (99 mod 2 = 1): reduce to gcd(2, 1)
- Step 3 (2 mod 1 = 0): reduce to gcd(1, 0)
- Since n = 0, Step 2 tells us the answer is 1! (Only 2 reductions compared to 49 subtractions!)
Solved Examples — The Three Long Division Ladder Diagrams (Page 49):
2 ) 99 ( 49
98
--
1 ) 2 ( 2
2
--
0 gcd = 1
375 ) 825 ( 2
750
---
75 ) 375 ( 5
375
---
0 gcd = 75
16 ) 60 ( 3
48
--
12 ) 16 ( 1
12
--
4 ) 12 ( 3
12
--
0 gcd = 4
8A Pinch of History — The Etymology of “Algorithm”
The influential Persian mathematician Muhammad ibn Mūsā al-Khwārizmī (780–850 CE), a renowned scholar at the famous “House of Wisdom” (Bayt al-Ḥikmah) in Baghdad, developed a great liking for Indian mathematics.
- He learnt Sanskrit, and around 820 CE wrote a detailed treatise expounding the Indian place-value number system and the Indian procedures for the four fundamental operations — addition, subtraction, multiplication, and division.
- His original Arabic manuscript was lost, but its 12th-century Latin translation, Liber Algorismi de numero Indorum (“The Book of Al-Khwārizmī on Indian Numerals”), survived and played a major role in spreading Indian arithmetic through medieval Europe.
- Al-Khwārizmī’s name became so closely tied to these methods that the word algorismus — from Algoritmi, the Latin form of his name — came to mean any Indian method for numerical computation; it later contracted to algorism and then algorithm.
9Divisor Pairs, Primes & Prime Factorisation
Divisors always occur in complementary pairs: if d divides n, then (n / d) is also a divisor of n, since d imes (n / d) = n.
Mathematical Proof 4: Why Examining Up to ⌊√(n) floor Finds All Divisors
- Suppose d is a divisor of n. Then there exists an integer d' such that d imes d' = n.
- If both d > √(n) and d' > √(n), then d imes d' > √(n) imes √(n) = n, which is a direct mathematical contradiction.
- Therefore, in every factor pair (d, d'), at least one of the factors must satisfy d ≤ √(n).
- Hence, testing all integers from 1 up to ⌊√(n) floor is guaranteed to discover all divisors of n without missing any. Q.E.D.
- For n = 18: ⌊√(18)
floor = 4. Testing 1, 2, 3, 4:
1 | 18 ⇒ (1, 18)
2 | 18 ⇒ (2, 9)
3 | 18 ⇒ (3, 6)
4 does not divide 18.
All divisors found in only 4 checks: \{1, 2, 3, 6, 9, 18\}. - For n = 100: ⌊√(100) floor = 10. Checking 1 … 10: (1, 100), (2, 50), (4, 25), (5, 20), (10, 10). All 9 divisors found in 10 checks!
- Prime Factorisation of 180: 180 = 2² imes 3² imes 5^1.
- Representation: In code/data structures, represent as key-value pairs
{2: 2, 3: 2, 5: 1}. - Finding GCD with 75 = 2^0 imes 3^1 imes 5²: Take the minimum exponent of each prime:
gcd(180, 75) = 2^{min(2,0)} imes 3^{min(2,1)} imes 5^{min(1,2)} = 2^0 imes 3^1 imes 5^1 = 15. - Finding LCM with 75: Take the maximum exponent of each prime:
ext{lcm}(180, 75) = 2^{max(2,0)} imes 3^{max(2,1)} imes 5^{max(1,2)} = 2² imes 3² imes 5² = 900.
10Chapter Summary — Key Principles
- An algorithm is a systematic procedure to solve a problem.
- Algorithms consist of basic steps that we know how to execute directly.
- We may execute the same step a number of times (e.g. for each j in 1, 2, …, n, check if j is a divisor of n).
- A step in an algorithm may be conditional (e.g. add j to list-of-divisors only if j divides n).
- When we describe an algorithm, we need to mathematically justify that it is correct.
- We analyse how many steps an algorithm takes in terms of the size of its input to evaluate its efficiency. Algorithms scaling with the number of digits are exponentially faster than those scaling with raw numeric magnitude.
Exercise Set 11.1 — Solutions
Precise column addition, place value, and the mechanics of carry.
1Add two 4-digit numbers using the steps we have written down. Make sure you follow the steps precisely; do not perform any action that is not explicitly mentioned. Are you able to obtain the correct result?
Step-by-step Execution of the Algorithm:
Let us choose the two 4-digit numbers: 4,738 and 2,695.
- Step 1 (Align right-to-left):
Write 4,738 above 2,695 with digits aligned at the units place:4 7 3 8
+ 2 6 9 5
--------- - Step 2 (Units column):
Add rightmost digits: 8 + 5 = 13. Since 13 > 10, write the units digit 3 below and set carry = 1. - Step 3 (Tens column):
Add digits and carry: 3 + 9 + 1 = 13. Since 13 > 10, write units digit 3 below and set carry = 1. - Step 4 (Repeat for Hundreds column):
Add digits and carry: 7 + 6 + 1 = 14. Since 14 > 10, write units digit 4 below and set carry = 1. - Step 4 (Repeat for Thousands column):
Add digits and carry: 4 + 2 + 1 = 7. Since 7 < 10, write 7 below and set carry = 0. - Step 5 (Final carry check):
Carry is 0, so no digit is added to the left.
2What happens if you add a 5-digit number to a 3-digit number. Do our steps handle this situation correctly?
Analysis & Minor Clarification:
- Right-to-Left Alignment: Step 1 instructs us to align digits from right to left. For example, adding 42,718 (5 digits) and 563 (3 digits):4 2 7 1 8
+ 5 6 3
----------- - Handling Missing Digits: When processing the thousands and ten-thousands columns, the 3-digit number has no digits written. In the place-value system, an empty place value represents 0 (i.e. 563 is equivalent to 00,563).
- Do the steps handle this?
• If we strictly interpret “add the two digits” when one is absent, a machine might pause unless instructed that an absent digit equals 0.
• With the standard rule that empty leading columns have digit value 0, Step 3 adds (2 + 0 + carry) and (4 + 0 + carry), producing the correct result 43,281.
3Why is it important to align the columns from right to left?
Place-Value Justification:
- Preservation of Place Value: In the Indian base-ten system, the position of a digit determines its multiplier (1, 10, 100, 1000, …). Aligning from right to left guarantees that digits with identical place values line up in the same vertical column (units with units, tens with tens, hundreds with hundreds).
- What would happen if aligned left-to-right?
If we added 523 and 41 by aligning left-to-right:5 2 3The 4 (which represents 40) would be added to 5 (which represents 500), falsely treating 40 as 400! This would produce a completely erroneous sum.
+ 4 1
-------
4In Step 3, why cannot the value of carry be more than 1?
Mathematical Proof by Induction:
- In any column, let the two digits be d1 and d2, and let the incoming carry be c.
- Since d1 and d2 are single decimal digits, their maximum possible value is 9.
- At the first column (units place), the incoming carry is 0. The maximum possible sum is 9 + 9 = 18. The tens digit (carry) is at most 1.
- For any subsequent column, the incoming carry c ≤ 1. The maximum possible column sum is:
Maximum Column Sum = 9 + 9 + 1 = 19 - Since 19 is strictly less than 20, its tens digit is 1. Thus, the new carry generated can never be greater than 1.
5What happens if we do not include the fifth step in the algorithm above? Give examples where the algorithm will work correctly and where it will fail to work.
Analysis of Step 5 (The Final Carry):
- Case 1 — Where the algorithm works correctly without Step 5:
When the sum of the leftmost digits (plus any incoming carry) is strictly less than 10, the final carry is 0. Step 5 does nothing, so omitting it causes no error.
• Example: 1,234 + 2,345 = 3,579. The leftmost addition is 1 + 2 = 3 (carry = 0). The answer 3,579 is completely correct. - Case 2 — Where the algorithm FAILS without Step 5:
When the leftmost column produces a sum ≥ 10, a carry of 1 is generated. Without Step 5, this carry is discarded, and the answer loses its most significant digit!
• Example 1: 473 + 695 = 1,168. Without Step 5, the leading 1 is omitted, giving the incorrect answer 168!
• Example 2: 9,999 + 1 = 10,000. Without Step 5, the answer becomes 0000 (0)!
Exercise Set 11.2 — Solutions
Sorted lists, LCM algorithm, and divisor pairs.
1Suppose List 1 and List 2 are two lists of numbers in increasing order.
(i) Write an algorithm to find elements in List 1 that are not present in List 2.
(ii) Write an algorithm to find elements in List 2 that are not present in List 1.
Two-Pointer Linear Scan Algorithms:
Because both lists are sorted in increasing order, we do not need to compare every element of List 1 with every element of List 2. We can scan both lists simultaneously in a single pass (like merging sorted decks of cards).
- (i) Algorithm: Elements in List 1 not in List 2 (Difference: List 1 − List 2):
• Step 1: Start with an empty list result = [ ].
• Step 2: Set index pointers i = 1 (for List 1) and j = 1 (for List 2).
• Step 3: While i ≤ length(List 1) and j ≤ length(List 2):
– If List 1[i] < List 2[j]: append List 1[i] to result, and increment i by 1.
– If List 1[i] == List 2[j]: increment i by 1 and increment j by 1 (it is present in both).
– If List 1[i] > List 2[j]: increment j by 1.
• Step 4: If List 2 is exhausted but List 1 has remaining elements: append all remaining elements of List 1 to result.
• Step 5: Output result. - (ii) Algorithm: Elements in List 2 not in List 1 (Difference: List 2 − List 1):
Apply the exact same algorithm with the roles of List 1 and List 2 swapped (or whenever List 2[j] < List 1[i], append List 2[j] to result and increment j; if List 1 ends first, append all remaining elements of List 2).
2Describe an algorithm to compute the least common multiple (lcm) of two numbers.
Two Algorithmic Approaches for LCM:
- Method 1 — Using the Fundamental GCD Relationship (Most Efficient):
For any two positive integers m and n:
lcm(m, n) × gcd(m, n) = m × n &implies lcm(m, n) = (m × n) / gcd(m, n)
Algorithm:
• Step 1: Compute g = gcd(m, n) using Åryabhaṭa’s / Euclid’s division algorithm.
• Step 2: Divide m by g to get q = m / g (dividing first prevents integer overflow with large numbers).
• Step 3: Compute lcm = q × n.
• Step 4: Return lcm. - Method 2 — Multiples Scan Algorithm (From First Principles):
• Step 1: Set multiple = max(m, n).
• Step 2: While multiple mod min(m, n) ≠ 0:
– multiple = multiple + max(m, n)
• Step 3: Report multiple as lcm(m, n).
Example for lcm(6, 8): Scan 8 (not div by 6), 16 (not div by 6), 24 (divisible by 6!). lcm = 24.
*3Divisors occur in pairs. For instance, the divisors of 18 are (1, 18), (2, 9) and (3, 6).
(i) If we write out divisors in pairs, how many numbers do we have to examine between 1 and n to find all the divisors of n?
(ii) If we list out the divisors in pairs, will our gcd algorithm still work in the manner we have described?
Step-by-step Solution:
- (i) How many numbers must be examined?
• For every divisor d ≤ √n, there is a paired divisor (n/d) ≥ √n.
• If both factors were strictly greater than √n, their product would exceed n (since √n × √n = n), which is impossible.
• Therefore, every factor pair has at least one member ≤ √n. We only need to examine integers from 1 up to ⌊√n⌋.
• Count of numbers examined: exactly ⌊√n⌋ numbers (for n = 10,000, instead of 10,000 checks, we only do 100 checks!). - (ii) Will our GCD algorithm still work?
• In our first GCD algorithm (Section 11.2.3), Step 5 reports the rightmost element of common-divisors, assuming the list is in strictly increasing order.
• If we discover divisors in pairs and append them as found — e.g. for 18: [1, 18, 2, 9, 3, 6] — the list is no longer sorted in increasing order.
• Modification required: The GCD algorithm will work correctly if we either:
(a) Sort the list of common divisors before reading the last element, or
(b) Maintain a variablemax_commonand update it with the largest common divisor found, or
(c) Insert the paired divisors from the right end of the list.
Exercise Set 11.3 — Solutions
Reverse scans and early termination optimizations.
1How would our original algorithm change if we computed the divisors of n by examining the numbers from 1 to n in reverse order, from n down to 1?
Step-by-step Analysis of Reverse Divisor Scan:
- Algorithm Modification:
• Step 2 changes from “For each j in 1, 2, …, n” to “For each j in n, n−1, n−2, …, 1”.
• Each time j divides n, j is added to list-of-divisors. - Consequences:
• Output Order: The list will be generated in strictly descending order (e.g. divisors(18) = [18, 9, 6, 3, 2, 1]).
• Number of Checks: The total number of checks remains exactly n, so scanning backwards does not reduce the workload if all divisors are needed.
2What about the last algorithm described above? What happens when we look at common divisors starting from min(m, n) and work backwards to 1?
Early Termination Breakthrough:
- The Backward Scan Procedure:
We start k at min(m, n) and count downwards: k = min(m, n), min(m, n) − 1, min(m, n) − 2, …, down to 1. - What happens when we find a divisor?
Because we are scanning from the largest possible divisor downwards, the very first number k that divides both m and n is guaranteed to be the GREATEST common divisor! - Immediate Termination:
We can stop immediately and return k without testing any of the remaining numbers!
• Best case: If n divides m, the first check (k = n) succeeds, and the algorithm terminates in just 1 step!
• Example: gcd(50, 100). The first check tests k = 50. Since 50 divides 100, it halts in 1 step! (The forward algorithm would have performed 50 steps).
End-of-Chapter Exercises — Solutions
Improved Euclidean division, divisibility proofs, prime tests, and prime factorisation.
1Compute the following using the improved version of Euclid's algorithm (Åryabhaṭa’s division by remainder).
(i) gcd(375, 825)
(ii) gcd(51000, 81000)
(iii) gcd(1789287, 237656)
(iv) gcd(2587392, 157656)
Step-by-step Division by Remainder for All Four Pairs:
- (i) gcd(375, 825):
• 825 ÷ 375 = 2 with remainder 75 &implies 825 = 375 × 2 + 75
• 375 ÷ 75 = 5 with remainder 0 &implies 375 = 75 × 5 + 0
gcd(375, 825) = 75 - (ii) gcd(51000, 81000):
• 81,000 = 51,000 × 1 + 30,000
• 51,000 = 30,000 × 1 + 21,000
• 30,000 = 21,000 × 1 + 9,000
• 21,000 = 9,000 × 2 + 3,000
• 9,000 = 3,000 × 3 + 0
gcd(51000, 81000) = 3,000 - (iii) gcd(1789287, 237656):
• 1,789,287 = 237,656 × 7 + 125,695
• 237,656 = 125,695 × 1 + 111,961
• 125,695 = 111,961 × 1 + 13,734
• 111,961 = 13,734 × 8 + 2,089
• 13,734 = 2,089 × 6 + 1,200
• 2,089 = 1,200 × 1 + 889
• 1,200 = 889 × 1 + 311
• 889 = 311 × 2 + 267
• 311 = 267 × 1 + 44
• 267 = 44 × 6 + 3
• 44 = 3 × 14 + 2
• 3 = 2 × 1 + 1
• 2 = 1 × 2 + 0
gcd(1789287, 237656) = 1 (The numbers are coprime!) - (iv) gcd(2587392, 157656):
• 2,587,392 = 157,656 × 16 + 64,896
• 157,656 = 64,896 × 2 + 27,864
• 64,896 = 27,864 × 2 + 9,168
• 27,864 = 9,168 × 3 + 360
• 9,168 = 360 × 25 + 168
• 360 = 168 × 2 + 24
• 168 = 24 × 7 + 0
gcd(2587392, 157656) = 24
2Assume that m ≥ n. Verify that d divides m and n if and only if d divides both n and m mod n.
Mathematical Proof (Bidirectional “If and only if”):
By the division algorithm, dividing m by n gives a quotient q and remainder r = m mod n such that:
m = qn + r ⇔ r = m − qn
- Forward Direction (⇒): If d divides m and d divides n, then d divides both n and (m mod n):
• Since d divides m and n, there exist integers a and b such that m = ad and n = bd.
• Substituting into r: r = m − qn = ad − q(bd) = (a − qb)d.
• Since (a − qb) is an integer, d divides r (which is m mod n).
• Therefore, d divides both n and m mod n. - Reverse Direction (⇐): If d divides n and d divides (m mod n), then d divides both m and n:
• Let r = m mod n. Since d divides n and r, there exist integers b and c such that n = bd and r = cd.
• Substituting into m: m = qn + r = q(bd) + cd = (qb + c)d.
• Since (qb + c) is an integer, d divides m.
• Therefore, d divides both m and n.
3Write an algorithm prime(n) to check if n is prime.
(Hint: A prime number p has exactly two distinct factors, 1 and p. Can you make use of divisors(n) to write out prime(n)?)
Formulation of prime(n):
- Method 1 — Using the Hint with divisors(n):
• Step 1: If n ≤ 1, report False (1 is not prime by definition).
• Step 2: Compute L = divisors(n) using the earlier divisor algorithm.
• Step 3: If length(L) == 2 (meaning its only divisors are [1, n]), report True.
• Step 4: Otherwise, report False. - Method 2 — Direct Optimized Algorithm (O(√(n)) trial division):
• Step 1: If n ≤ 1, return False.
• Step 2: If n == 2, return True.
• Step 3: If n mod 2 == 0, return False.
• Step 4: For each odd integer j from 3 up to ⌊√n⌋:
– If n mod j == 0, return False (composite).
• Step 5: Return True (prime).
*4Write an algorithm primedivisors(n) to compute the list of divisors of n that are prime numbers.
(Hint: Compute divisors(n) and then filter out the primes in this list.)
Algorithm primedivisors(n):
- Step 1: Start with an empty list prime-divisors = [ ].
- Step 2: Compute all-divisors = divisors(n).
- Step 3: For each number d in all-divisors:
– Check if prime(d) is True.
– If True, append d to prime-divisors. - Step 4: Return prime-divisors.
- all-divisors(180) = [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180]
- Testing each: 1 is not prime; 2 is prime; 3 is prime; 4 not; 5 is prime; 6, 9, 10, 12, … are all composite.
- Output: [2, 3, 5].
*5We can also find the gcd of two numbers by computing prime factorisation of both the numbers. Try to write an algorithm to compute the prime factorisation of a number.
(i) The prime factorisation of 180 is 22 × 32 × 51. How would you represent this?
(ii) How would you compare the prime factorisations of two numbers?
Step-by-step Solution:
- Algorithm to Compute Prime Factorisation of n:
• Step 1: Set temp = n, d = 2, and start with an empty mapping factors = { }.
• Step 2: While d × d ≤ temp:
– count = 0
– While temp mod d == 0:
count = count + 1
temp = temp / d
– If count > 0: record factor d with exponent count (e.g. factors[d] = count).
– d = d + 1
• Step 3: If temp > 1: record factors[temp] = 1.
• Step 4: Return factors. - (i) Representing 180 = 22 × 32 × 51:
• Representation A (Key-Value Dictionary / Map):{2: 2, 3: 2, 5: 1}where keys are prime bases and values are exponents.
• Representation B (List of Pairs):[(2, 2), (3, 2), (5, 1)].
• Representation C (Expanded prime multiset):[2, 2, 3, 3, 5]. - (ii) Comparing Prime Factorisations of m and n:
• Align all primes appearing in either factorisation, assigning exponent 0 to any prime missing in one of the numbers.
• To find GCD: Take the minimum exponent for each prime:
gcd(m, n) = ∏ pimin(expm, expn)
• To find LCM: Take the maximum exponent for each prime:
lcm(m, n) = ∏ pimax(expm, expn)
• Example: 180 = 22 × 32 × 51 and 75 = 20 × 31 × 52:
– gcd = 2min(2,0) × 3min(2,1) × 5min(1,2) = 20 × 31 × 51 = 15.
– lcm = 2max(2,0) × 3max(2,1) × 5max(1,2) = 22 × 32 × 52 = 900.
Mini Test - 10 Questions
Select one option for each question.