Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- O(1):
- // Here c is a constant
- for (int i = 1; i <= c; i++) {
- // some O(1) expressions
- }
- O(n):
- // Here c is a positive integer constant
- for (int i = 1; i <= n; i += c) {
- // some O(1) expressions
- }
- O(n^2):
- for (int i = 1; i <=n; i += c) {
- for (int j = 1; j <=n; j += c) {
- // some O(1) expressions
- }
- }
- O(logn):
- for (int i = 1; i <=n; i *= c) {
- // some O(1) expressions
- }
- Explanation:
- 1, c, c^2, c^3, … c^k
- c^k <= n
- k <= logn
- O(sqrt(n)):
- for (int i = 1; i*i <=n; i++) {
- // some O(1) expressions
- }
- Explanation:
- 1, 4, 9, 16, .... , k^2
- k^2 <= n
- k <= sqrt(n)
- O(n+m):
- for (int i = 1; i <=m; i += c) {
- // some O(1) expressions
- }
- for (int i = 1; i <=n; i += c) {
- // some O(1) expressions
- }
- if n==m : O(2n) equivalent to O(n)
- //For Exercise:
- O(loglog(n)):
- // Here c is a constant greater than 1
- for (int i = 2; i <=n; i = pow(i, c)) {
- // some O(1) expressions
- }
- Explanation:
- In this case, i takes values 2, 2^c, (2^c)^c = 2^c2, (2^c2)^c = 2^c3, …, 2^C^k
- 2^C^k <= n
- C^k <= logn
- k <= loglogn
- O(sqrt(n)):
- c = 0;
- for(int i = 1; c<=n; i++)
- {
- c = c+i;
- }
- Explanation:
- i c
- -- --
- 1 1
- 2 1+2
- 3 1+2+3
- 4 1+2+3+4
- . .
- . .
- k 1+2+3+4+....+k
- 1+2+3+4+....+k <= n
- k(k+1)/2 <= n
- k^2 <= n
- k = sqrt(n)
- O(log(n)):
- c = 0
- for(int i = 1; i<=n; i=i*2)
- {
- c = c+1;
- }
- for(int j = 1; j<=c; j=j*2)
- {
- // O(1) operation
- }
- Explanation:
- complexity of 1st for loop : c = O(logn)
- complexity of 2nd for loop : k = O(logC)
- O(logN + logC)
- O(logN + loglogN)
- HOME WORK:
- while(m!=n)
- {
- if(m>n) m = m-n;
- else n = n-m;
- }
- Ans: O(n)
- ///Prefix Sum:
- 5 1 2 4 1 0 2 3 5 7 1 2
- 5 6 8 12 13 13 15 18 23 30 31 33
- sum[0] = 0
- sum[i] = sum[i-1] + a[i];
- ans = sum[R] - sum[L-1];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement