Escolar Documentos
Profissional Documentos
Cultura Documentos
i, j := 1, n; loc := 0;
do (i ≤ j) → m := ⎣(i+j)/2⎦ ;
if x > am → i := m+1
| x = am → loc := m; i, j := m, m-1;
| x < am → j := m−1
fi
od
[(loc≤n) ⇒ (x = aloc)] ∨⋅ [(loc=0) ⇒ (1≤∀k≤n: x ≠ ak)]
if x ≥ y → m := x if x > y → m := x if x ≥ y → m := x
| x < y → m := y | x ≤ y → m := y | x ≤ y → m := y
fi fi fi
(m=x ∨ m=y) ∧ m≥x ∧ m<y
(m=x ∨ m=y) ∧ m>x ∧ m≥y
(m=x ∨ m=y) ∧ m≥x ∧ m≥y
?P
recover P
P
Loop invariance P
Loop invariance P should be initialized before the loop,
Loop invariance P must be recovered in the loop, if destroied, and
Loop invariance P is still valid after(termination of) the loop.
P ∧ ¬BB is the final condition that you want after the loop!
a, b, c, d := A, B, C, D;
do a > b → a, b := b, a
| b > c → b, c := c, b
| c > d → c, d := d, c
od
¬BB = (a ≤ b) ∧ (b ≤ c) ∧ (c ≤ d)
= a ≤ b ≤ c ≤ d.
What is the loop invariance of the above do-od loop?
P = a, b, c, and d are permutation of A, B, C, and D.
Loop invariance P should be strong enough to get final result
with and ¬BB;
whereas weak enough
to be easily initialized and be still valid inside the loop.
P ∧ ¬BB is the final condition that you want.
Greedy algorithm
Optimization problem
to find a solution to the given problem that
either minimizes or maximizes the value of some parameters
(global) optimal
to select the best choise considering all sequences of steps
local optimal(greddy algorithm)
to select the best choise at each step
The constant c and k are called the witnesses of ... f(x) is O(g(x)).
Assume c and k are smallest witnesses, Then ∀c’, k’ .∋. c < c’, x < x’,
c’ and k’ are also witnesses
Example 1, 2, 3, 4
Theorem 1 Let f(x) = anxn + an-1xn-1 + … + a1x + a0. Then f(x) is O(xn).
proof easy with witness k=1 and c = Σ |ai|.
Example 6 n!
n! ≤ nn. n! is O(nn) with witness k=1 and c=1.
log n! ≤ log nn = n log n
Definition Let g: N or R → R.
O(g) = {f: N or R → R| ∃c, k > 0 ∀x > k: |f(x)| ≤ c|g(x)|}
If f ∈ O(g), f glows at most order of g.
O(1) ⊂ O(log n) ⊂ O(n) ⊂ O(nlog n) ⊂ O(n2) ⊂ O(n3)⊂ … O(2n) ⊂ O(n!)
Worst-case analysis
Average-case analysis
(totally) solvable
tractable
polynomial
intractable
exponential
class P
polynomial, tractable
Theorem 1 ∀a, b, c ∈ Z.
i) (a | b) ∧ (a | c) ⇒ a | (b+c).
ii) (a | b) ⇒ a | bc.
iii) (a | b) ∧ (b | c) ⇒ a | c.
Modular Arithmetic
Definition 3 Let a, b ∈ Z, m ∈ Z+. Then a is congruent to b modulo m,
written a ≡ b (mod m) or b ∈ [a]mod m, if m | (a - b).
Theorem 3 a ≡ b (mod m), iff a mod m = b mod m.
or (a - b) mod m = 0.
Theorem 4 a ≡ b (mod m), iff ∃k ∈ Z: a = b + km.
Theorem 5 If a ≡ b (mod m) ∧ c ≡ d (mod m), then
a + c ≡ b + d (mod m) ac ≡ bd (mod m).
3.8 Matrices