Professional Documents
Culture Documents
Rahul Narain
...
....
....
4
5
100
101
... 6
7
110
111
8 1000
In decimal, ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 9 1001
#dots = “14” = 1 ten + 4 ones 10 1010
11 1011
In binary, only two digits: 0, 1 12 1100
#dots = “1110” = 1 eight + 1 four + 1 two + 0 ones 13 1101
14 1110
15 1111
16 10000
.. ..
. .
1 1 1 0 1 1
9 1 0 0 1
1 10 1
0 0 1 1
0
2 0 1 0 1 0 0
(
0 if b = 0,
a×b =
a + a × (b − 1) otherwise.
(
1 if n = 0,
n! =
(n − 1)! × n otherwise.
Last exercise: computing x n
(
1 if n = 0,
power(x; n) =
x · power(x; n − 1) otherwise.
def power(x,n):
# Raises a number to a nonnegative integer power.
if n == 0:
return 1
else:
return x * power(x, n-1)
Bisection
√
Problem: Given a natural number n, find the natural number k = b nc,
i.e. the largest natural number such that k 2 ≤ n.
√
b 0c = 0
√ √ √
b 1c = b 2c = b 3c = 1
√ √ √
b 4c = b 5c = · · · = b 8c = 2
def isqrt(n):
# The integer square root of a given natural number.
return bisect(0, n, n)
Actually, this algorithm doesn’t work!! Try evaluating isqrt(1).
√
Hint: k is exactly equal to b nc if and only if k 2 ≤ n and √ ...?
Otherwise, it is either strictly less or strictly greater than b nc.
Practice exercises
1
Base case: For n = 0, LHS is 0 and RHS is 2
· 0 · 1 = 0.
Induction step: Assume 1 + 2 + · · · + n = 12 n(n + 1) (induction
hypothesis).
We have to show that 1 + 2 + · · · + n + (n + 1) = 12 (n + 1)(n + 2).
1 + 2 + · · · + n +(n + 1) = 12 n(n + 1) + (n + 1)
| {z }
= 12 (n + 1)(n + 2):
“Strong” doesn’t mean it can prove more things than “weak” induction,
only that we are allowed to use a stronger hypothesis in the induction step.
(Actually both versions of induction are equivalent!)
Example: Recall the Fibonacci numbers, defined by
F0 = 0;
F1 = 1;
Fn = Fn−1 + Fn−2 for all n ≥ 2:
√
1+ 5
Let ffi = 2
≈ 1:618 : : : , which has the property that ffi2 = ffi + 1.
Show that Fn ≤ ffin−1 for all n ≥ 0.
Base case: F0 = 0 ≤ ffi−1 .
Induction hypothesis: For some n ≥ 1, Fm ≤ ffim−1 for all 0 ≤ m < n.
Induction step: We need to show that Fn ≤ ffin−1 .
Fn = Fn−1 + Fn−2
≤ ffin−2 + ffin−3
= ffin−3 (ffi + 1)
= ffin−3 ffi2
= ffin−1 :
mod(a; b) = . . . do it yourself ^
¨
Claim: For all natural numbers n ≥ 0 and d > 0, div(n; d) computes the
quotient when n is divided by d. That is, if q = div(n; d), then
n = q × d + r for some 0 ≤ r < b.
We will prove this by induction. . . on which variable?
Base case: If n = 0, then q = 0, so n = q × d + r for r = 0.
Induction hypothesis: For all 0 ≤ m < n, if q = div(m; d) then
m = q × d + r for some 0 ≤ r < d.
Induction step:
If n < d, then q = div(n; d) = 0, so n = q × d + r for r = n.
If n ≥ d, then q = div(n; d) = div(n − d; d) + 1.
Let div(n − d; d) = q 0 , so q = q 0 + 1. By the induction hypothesis,
n − d = q 0 × d + r for some 0 ≤ r < d. So
n = (q 0 × d + r ) + d
= (q 0 + 1) × d + r
=q×d +r