9.5.3. 복잡도 증명
9.4.4절의 reverseSlow_bigO는 연결 방식의 비용에 이차 상한을 준다. 9.4절에서 선형 함수에도 이차 상한을 줄 수 있었다. 이차 차수를 확정하려면 연결 방식의 비용이 일정한 배수의 n^2보다 계속 크거나 같다는 하한도 보인다.
연결 방식의 비용을 T_{\mathrm{slow}}(n)이라 쓰자. 삼각수 공식의 두 배 형태를 전개하면 2T_{\mathrm{slow}}(n)=n^2+n이다. 여기서 n\ge0이므로 n^2\le 2T_{\mathrm{slow}}(n)이다. BigOmega를 펼치면 BigO의 두 함수가 뒤바뀐 목표가 되므로 상수를 2, 임계값을 0으로 고른다. 이 부등식은 실수로 읽으면 \tfrac12n^2\le T_{\mathrm{slow}}(n)이라는 하한이다. Lean 코드에서는 두 배의 정수를 비교한다.
theorem reverseSlow_bigOmega :
BigOmega reverseCostBySize (fun n => n * n) := ⊢ BigOmega reverseCostBySize fun n => n * n
⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n * n) n ≤ c * reverseCostBySize n
refine ⟨2, ⊢ 0 < 2 All goals completed! 🐙, 0, ?_⟩
n:Nata✝:0 ≤ n⊢ (fun n => n * n) n ≤ 2 * reverseCostBySize n
n:Nata✝:0 ≤ n⊢ n * n ≤ 2 * reverseCostBySize n
n:Nata✝:0 ≤ nh:2 * reverseCostBySize n = n * (n + 1)⊢ n * n ≤ 2 * reverseCostBySize n
n:Nata✝:0 ≤ nh:2 * reverseCostBySize n = n * n + n⊢ n * n ≤ 2 * reverseCostBySize n
omega All goals completed! 🐙
theorem reverseSlow_bigTheta :
BigTheta reverseCostBySize (fun n => n * n) :=
⟨reverseSlow_bigO, reverseSlow_bigOmega⟩
그림 9.15에서 연결 방식의 비용은 길이가 1 이상일 때 n^2/2와 n^2 사이에 놓인다. reverseSlow_bigTheta는 이 관계를 9.4절의 상한 정리와 방금 증명한 하한 정리의 논리곱으로 표현한다.
누산기 방식에서는 비용과 비교 함수가 둘 다 n이다. 상한과 하한 모두 상수 1, 임계값 0으로 증명할 수 있다. 따라서 이 모델에서 누산기 방식은 \Theta(n), 연결 방식은 \Theta(n^2)이다.
theorem reverseFast_bigO :
BigO reverseFastCostBySize (fun n => n) := by ⊢ BigO reverseFastCostBySize fun n => n
unfold BigO ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → reverseFastCostBySize n ≤ c * (fun n => n) n
refine ⟨1, by ⊢ 0 < 1 decide All goals completed! 🐙, 0, ?_⟩
intro n _ n:Nata✝:0 ≤ n⊢ reverseFastCostBySize n ≤ 1 * (fun n => n) n
simp [reverseFastCostBySize] All goals completed! 🐙
theorem reverseFast_bigOmega :
BigOmega reverseFastCostBySize (fun n => n) := by ⊢ BigOmega reverseFastCostBySize fun n => n
unfold BigOmega BigO ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n) n ≤ c * reverseFastCostBySize n
refine ⟨1, by ⊢ 0 < 1 decide All goals completed! 🐙, 0, ?_⟩
intro n _ n:Nata✝:0 ≤ n⊢ (fun n => n) n ≤ 1 * reverseFastCostBySize n
simp [reverseFastCostBySize] All goals completed! 🐙
theorem reverseFast_bigTheta :
BigTheta reverseFastCostBySize (fun n => n) :=
⟨reverseFast_bigO, reverseFast_bigOmega⟩
- 연습문제 9.5.1 증가율이 같은 두 비용 함수 비교하기
아래 두 함수에 대해
BigTheta costA (fun n => n)과BigTheta costB (fun n => n)을 증명한다. 이어 모든n : Nat에서costB n < costA n임을 증명한다. 정확한 비용의 부등식과 점근적 증가율이 같다는 정리를 각각 해석한다.def costA (n : Nat) : Nat := 5 * n + 3 def costB (n : Nat) : Nat := 2 * n + 1