When can an algorithm have square root(n) time complexity?

前端 未结 6 1067
攒了一身酷
攒了一身酷 2021-02-01 15:11

Can someone give me example of an algorithm that has square root(n) time complexity. What does square root time complexity even mean?

6条回答
  •  耶瑟儿~
    2021-02-01 15:29

    Primality test

    Solution in JavaScript

     

    const isPrime = n => {
        for(let i = 2; i <= Math.sqrt(n); i++) {
            if(n % i === 0) return false;
        }
        return true;
    };
    

    Complexity

    O(N^1/2) Because, for a given value of n, you only need to find if its divisible by numbers from 2 to its root.

提交回复
热议问题