Divide and Conquer: Numbers and Searches
This lesson applies the paradigm and its analysis to a first set of classic problems: the factorial, sequential and binary search, the Fibonacci numbers and the greatest common divisor. Some of them show the strength of divide and conquer; others, especially Fibonacci, show what happens when it is applied badly. All of them are implemented, with tests, in the course repository.
- How to write and analyze recursive versions of simple problems (factorial, searches).
- Why the naive recursive Fibonacci is exponential, how much work it repeats, and several much better alternatives, down to a logarithmic one.
- Why Euclid's algorithm for the greatest common divisor is so fast, and why "fast" must be measured in the size of the input.
Factorial of a Number
The factorial has a natural recursive definition:
public long factorialRecursive(int n) {
if (n < 0) throw new IllegalArgumentException("Undefined for negative numbers");
if (n == 0 || n == 1) return 1; // base case
return n * factorialRecursive(n - 1); // one subproblem of size n - 1
}
Analysis. Divide and conquer by subtraction: (one subproblem), (size ), (a constant amount of work: one multiplication). Since : .
It is a reduction (), so it can easily be written as a loop, which avoids a recursion of depth :
public long factorialIterative(int n) {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
Both are in time, but the iterative version needs extra memory instead of stack frames. (And remember from the first chapter: with long, the result overflows for .)
Sequential and Binary Search
Sequential search by subtraction
To find the position of an element x in a vector, examine the first element of the remaining part; if it is not x, search in the rest:
private int searchBySubtraction(int i, int[] v, int x) {
if (i == v.length) return Integer.MIN_VALUE; // base case: nothing left, not found
if (v[i] == x) return i; // base case: found
return searchBySubtraction(i + 1, v, x); // one subproblem of size n - 1
}
, , : in the worst case, like the iterative version, but with a recursion depth of up to .
Binary search by division
If the vector is sorted, compare x with the central element, and search only in the half where it can be:
private int searchByDivision(int left, int right, int[] v, int x) {
if (left > right) return Integer.MIN_VALUE; // empty part: not found
int center = left + (right - left) / 2;
if (v[center] == x) return center;
else if (v[center] > x) return searchByDivision(left, center - 1, v, x);
else return searchByDivision(center + 1, right, v, x);
}
Although the code contains two recursive calls, only one of them is executed in each invocation: , , . Since (): , the result we obtained by counting iterations in the first chapter.
🧠 Checkpoint: How deep is binary search?
Question: With the code above, how many calls does searchByDivision make, at most, on a sorted vector of 1,000,000 elements?
Answer: At most 21: each call halves the part, and , so about 20 halvings reach a part of one element; an unsuccessful search makes one more call on an empty part. A sequential search may need a million comparisons.
The Fibonacci Numbers
The Fibonacci sequence is , where each number is the sum of the previous two:
A bit of history
The sequence is named after Leonardo of Pisa, known as Fibonacci, who described it in his Liber Abaci (1202), the book that popularised Hindu-Arabic numerals in Europe (the same numerals that al-Khwarizmi had described four centuries earlier). He presented it as the solution of a puzzle about the growth of a population of rabbits: starting with one pair, if every pair produces a new pair each month from its second month of life, how many pairs are there after months? The number of pairs each month follows exactly the sequence . Similar sequences had already been described centuries earlier by Indian mathematicians, in the study of poetic metres.
Huge numbers
Fibonacci numbers grow exponentially. It can be proved that for ; more precisely, is the nearest integer to , where is the golden ratio.
- has 209 digits.
In Java, a long can hold up to ; already overflows. For larger values, BigInteger is needed.
The naive recursive version
The definition translates directly into code:
public long fibonacciNaiveRecursive(int n) {
if (n <= 1) return n;
return fibonacciNaiveRecursive(n - 1) + fibonacciNaiveRecursive(n - 2);
}
Analysis. It is divide and conquer by subtraction with two subproblems, but of different sizes ( and ), so the formula does not apply directly. We can bound it:
- If the recursive part were : , , , so .
- If it were : , , , so .
The real algorithm is between both: . Solving the recurrence exactly gives : exponential.
Why is it so slow? Repeated work
Look at the calls for :
is computed twice, three times, five times... The subproblems are not independent: the same ones are solved again and again. In total, computing this way requires calls: more than 2.6 million calls for , and more than 40,000 million for .
We measured it: took 7 ms, 49 ms, 558 ms and 6.3 seconds. Each time increases by 5, the time is multiplied by about 11, which is . At that rate, would take millions of years.
Repeating the solution of the same subproblems is the hallmark of problems for which divide and conquer is not the right tool. The remedy, storing the solutions of subproblems so that each one is computed only once, is the core idea of dynamic programming, which you will study later. You can watch the difference in the Fibonacci visualization by David Galles.
Better implementations
- Iterative: O(n)
- With a table: O(n)
- Tail recursive: O(n)
- Logarithmic: O(log n)
Compute the numbers from the bottom up, keeping only the last two:
public long fibonacciIterative(int n) {
if (n == 0) return 0;
long n1 = 0, n2 = 1;
for (int i = 2; i <= n; i++) {
long sum = n1 + n2;
n1 = n2;
n2 = sum;
}
return n2;
}
Linear time and constant memory. Each subproblem is solved exactly once.
Store all the values in a vector. This uses memory, but it is the typical structure of a dynamic programming solution, and it keeps every value available in case it is needed later:
public long fibonacciArray(int n) {
if (n <= 1) return n;
long[] v = new long[n + 1];
v[0] = 0;
v[1] = 1;
for (int i = 2; i <= n; i++)
v[i] = v[i - 1] + v[i - 2];
return v[n];
}
A recursive version that carries the last two values as parameters, so that there is a single recursive call (, , : ):
public long fibonacciTailRecursive(int n) {
return tailHelper(0, 1, n);
}
private long tailHelper(long n1, long n2, int n) {
if (n == 0) return n1;
if (n == 1) return n2;
return tailHelper(n2, n1 + n2, n - 1);
}
The recursive call is the last operation of the method (a tail call). Some languages optimize such calls so that they use no extra stack; Java does not, so the recursion depth is still .
Fibonacci numbers satisfy a matrix identity:
So computing reduces to raising a matrix to the power , and powers can be computed by divide and conquer: if is even, and if it is odd. Each step halves the exponent: , , , so multiplications. The course repository contains a compact iterative implementation of this idea, fibonacciLogarithmic, which processes the bits of :
public long fibonacciLogarithmic(int n) {
if (n == 0) return 0;
long i = 1, j = 0, k = 0, h = 1, t;
while (n > 0) {
if (n % 2 == 1) { // odd exponent: multiply by the current power
t = j * h;
j = i * h + j * k + t;
i = i * k + t;
}
t = h * h; // square the current power
h = 2 * k * h + t;
k = k * k + t;
n = n / 2; // halve the exponent
}
return j;
}
(With long values, all versions overflow beyond ; the logarithmic algorithm shows its real advantage with BigInteger and very large .)
| Version | Time | Extra memory |
|---|---|---|
| Naive recursive | , exponential | stack |
| Iterative | ||
| With a table | ||
| Tail recursive | stack in Java | |
| Logarithmic (fast exponentiation) |
The Greatest Common Divisor
The greatest common divisor of two integers and is the largest integer that divides both. It has many applications: simplifying fractions, cryptography (the RSA algorithm relies on it), or computing the least common multiple.
A first approach
Try every candidate from 1 up to the smaller of the two numbers, and keep the largest that divides both:
public long naiveGCD(long a, long b) {
long gcd = 1;
for (long d = 1; d <= Math.min(a, b); d++)
if (a % d == 0 && b % d == 0)
gcd = d;
return gcd;
}
It is correct, and it looks linear, . But what is the size of the input here? A number is written with about digits (or bits). For numbers of 20 digits, the loop would run up to times: exponential in the number of digits. When the input is a number, the right measure of its size is the number of digits, not its value.
Euclid's algorithm
We can do much better by knowing something about the problem. Euclid's key observation is that, for , : any common divisor of and also divides the remainder , and vice versa. And the remainder is smaller than , so the problem shrinks:
- If , then , and we stop.
- Otherwise, compute and find with the same scheme.
private long euclidean(long a, long b) {
if (b == 0) return a; // base case
return euclidean(b, a % b); // one subproblem, much smaller
}
For example: . Two divisions, three calls.
Analysis. It can be shown that every two steps, the first argument is at least halved. So the scheme behaves like division by 2 with a single subproblem and constant work: , , , which gives , where is the value of the numbers. That is linear in the number of digits. The worst case occurs with two consecutive Fibonacci numbers, and Lamé's theorem states that the number of divisions is at most five times the number of decimal digits of the smaller number. For example, for two numbers of 100 digits, our tests needed 475 divisions in the worst case (consecutive Fibonacci numbers) and about 190 for random numbers, each one a single division. The naive approach would need up to iterations.
Euclid's algorithm illustrates an important lesson: finding the best algorithm often requires knowing something interesting about the problem. The naive approach only uses the definition of the GCD; Euclid's uses a mathematical property, and the gain is enormous.
- Taking the value as the size of a numeric input. The size is the number of digits: the naive GCD is exponential in it.
- Copying the subarray in each recursive call.
Arrays.copyOfRangecosts per call; pass the limits instead. - Trusting the naive recursive Fibonacci. It is exponential; the iterative version is .
🧠 Checkpoint: Trace Euclid's algorithm
Question: Compute with Euclid's algorithm. How many calls are made?
Answer: 21, since , and . Three divisions and four calls.
Summary
- The factorial and recursive sequential search are subtraction schemes with : , but with recursion depth . Iterative versions are preferable.
- Binary search is a division scheme with , , : . Count the calls executed, not the ones written.
- The naive recursive Fibonacci is exponential, , because it solves the same subproblems many times. Iterative versions are , and fast exponentiation of a matrix gives .
- For numerical inputs, the size is the number of digits. The naive GCD is exponential in the number of digits; Euclid's algorithm is linear in it.
Practice
- 🐇 Count the calls. Instrument the naive Fibonacci to count its calls, and check the formula for .
- ⏱️ Measure. Measure the naive, iterative and logarithmic versions of Fibonacci for increasing (lab session 3). For which does the naive version exceed one minute on your computer?
- 🔢 BigInteger. Rewrite the iterative and logarithmic versions with
BigIntegerand compute with both. Which one is faster, and why is the difference smaller than versus suggests? (Hint: what is the cost of multiplying two numbers with thousands of digits?) - ➗ Euclid by hand. Compute with Euclid's algorithm, writing each step. How many divisions are needed?
- ⚡ Fast power. Write a divide and conquer method that computes for an integer with multiplications, and identify , and .
Errors, suggestions and public questions open a form on GitHub, visible to everyone.