What is the time complexity?

Revision en1, by twocf22, 2021-07-22 22:09:45

First Code:

int ans = 0;
for (int i = 1; i <= n; i++) {
  for (int j = 1; j <= n; j++) {
    if ((i + j) % 2 == 0) ans += 1;
  }
}

The time complexity of this code is $$$O(n^2)$$$

Second Code:

if ((1 + 1) % 2 == 0) ans += 1;
if ((1 + 2) % 2 == 0) ans += 1;
if ((1 + 3) % 2 == 0) ans += 1;
if ((1 + 4) % 2 == 0) ans += 1;
if ((1 + 5) % 2 == 0) ans += 1;
.........
if ((n + n) % 2 == 0) ans += 1;

Is the complexity of this code same as the first code? Or is it $$$O(1)$$$ ?.

Thank You.

Tags #time complexity

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English twocf22 2021-07-22 22:11:35 5 .
en1 English twocf22 2021-07-22 22:09:45 568 . (published)