1 / 9

BIG OH

BIG OH. Problem: Design an algorithm to sum natural numbers up to 1 million terms. N = {1,2,3,4,5.......................1000000} OR Sum of N = {1+2+3+……….+1000000}. Algorithm-1. N = {1+2+3+……+1000000} int sum = 0; int n = 1000000; for ( int i = 1; i<=n; i++) {

wyatt
Télécharger la présentation

BIG OH

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BIG OH Sadiq Ahmad. BSCS-1. Main Campus

  2. Problem: Design an algorithm to sum natural numbers up to 1 million terms. N = {1,2,3,4,5.......................1000000} OR Sum of N = {1+2+3+……….+1000000} Sadiq Ahmad. BSCS-1. Main Campus

  3. Algorithm-1 N = {1+2+3+……+1000000} int sum = 0; int n = 1000000; for(int i = 1; i<=n; i++) { sum = sum+i; } println(sum); • A “for” loop is used to solve the problem. • The loop will run 1million time for this problem. • We assume that 1 loop cycle is consuming 1 machine cycle. Sadiq Ahmad. BSCS-1. Main Campus

  4. Algorithm-2 N={1+2+3+…..…+1000000} int first= 1; int last = 1000000; int n = 1000000; int step1, step2, step3 = 0; step1 = first+ last; step2 = n*step1; step3 = step2/2; println(step3); Above formula is used to solve the problem, It will give the sum in just 3 steps, and we assume 1 step consumes 1 machine cycle. Sadiq Ahmad. BSCS-1. Main Campus

  5. Quick Comparison Algorithn-1 Algorithm-2 It takes 3 cycles for any number of terms. It is constant in behavior, T(N) = 3. • It takes n cycles for n number of terms. • It is linear in behavior, T(N) = N. Sadiq Ahmad. BSCS-1. Main Campus

  6. Formal definition: Let Tand fbe two functions and T(N) is O(f(N)) if there are positive constant C and K such that T(N) <= C f(N) for all C > K. Sadiq Ahmad. BSCS-1. Main Campus

  7. Prove Big OH by definition As T(N) is O f(N) By definition. T(N) ≤ C f(N) for all C > K. T(N)=3 & f(N)=N 3 ≤ CN dividing both sides by N. 3/N ≤ C Hence Proved. Sadiq Ahmad. BSCS-1. Main Campus

  8. Ranking of Big Os w.r.t Behavior Sadiq Ahmad. BSCS-1. Main Campus

  9. Questions? Sadiq Ahmad. BSCS-1. Main Campus

More Related