90 likes | 269 Views
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++) {
E N D
BIG OH Sadiq Ahmad. BSCS-1. Main Campus
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
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
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
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
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
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
Ranking of Big Os w.r.t Behavior Sadiq Ahmad. BSCS-1. Main Campus
Questions? Sadiq Ahmad. BSCS-1. Main Campus