Why does this code have complexity O(1)?
function logAtMost5(n) {
for ( let i = 1; i <= Math.min(5,n); i {
console.log(i)
}
}
CodePudding user response:
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).
CodePudding user response:
Simply because the for loop will not iterate more than 5 times, it's iterations will not exceed a fixed constant.