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

前端 未结 6 972
攒了一身酷
攒了一身酷 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:47

    There are many cases. These are the few problems which can be solved in root(n) complexity [better may be possible also].

    • Find if a number is prime or not.
    • Grover's Algorithm: allows search (in quantum context) on unsorted input in time proportional to the square root of the size of the input.link
    • Factorization of the number.

    There are many problems that you will face which will demand use of sqrt(n) complexity algorithm.

    As an answer to second part:

    sqrt(n) complexity means if the input size to your algorithm is n then there approximately sqrt(n) basic operations ( like **comparison** in case of sorting). Then we can say that the algorithm has sqrt(n) time complexity.

    Let's analyze the 3rd problem and it will be clear.

    let's n= positive integer. Now there exists 2 positive integer x and y such that
         x*y=n;
         Now we know that whatever be the value of x and y one of them will be less than sqrt(n). As if both are greater than sqrt(n) 
      x>sqrt(n) y>sqrt(n) then x*y>sqrt(n)*sqrt(n) => n>n--->contradiction.
    

    So if we check 2 to sqrt(n) then we will have all the factors considered ( 1 and n are trivial factors).

    Code snippet:

       int n;
       cin>>n;
       print 1,n;
       for(int i=2;i<=sqrt(n);i++) // or for(int i=2;i*i<=n;i++)
         if((n%i)==0)
           cout<

    Note: You might think that not considering the duplicate we can also achieve the above behaviour by looping from 1 to n. Yes that's possible but who wants to run a program which can run in O(sqrt(n)) in O(n).. We always look for the best one.

    Go through the book of Cormen Introduction to Algorithms.

    I will also request you to read following stackoverflow question and answers they will clear all the doubts for sure :)

    1. Are there any O(1/n) algorithms?
    2. Plain english explanation Big-O
    3. Which one is better?
    4. How do you calculte big-O complexity?

提交回复
热议问题