Lucas Lomeu
Lucas Lomeu

Reputation: 31

Big O Complexity function

Why does this code have complexity O(1)?

function logAtMost5(n) {
  for ( let i = 1; i <= Math.min(5,n); i++ {
    console.log(i)
  } 
}

Upvotes: 0

Views: 30

Answers (2)

Zoe Leullier
Zoe Leullier

Reputation: 46

Simply because the for loop will not iterate more than 5 times, it's iterations will not exceed a fixed constant.

Graph of y = min(x,5)

Upvotes: 2

0xRyN
0xRyN

Reputation: 872

This function does at most 5 iterations. Which is a constant.

A constant has O(1) complexity.

If there was n instead of Math.min(5,n), it would have n iterations which would be linear O(n).

Upvotes: 2

Related Questions