Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Check whether the given number is a perfect square

Objec­tive:  Given an inte­ger check whether it is a per­fect square.


number = 37
Output: false

number = 49
Output: true

This is fun puz­zle which is asked in the inter­view.

  1. Say num­ber is n.
  2. Start a loop from 1 to n/2.
  3. Dur­ing iter­a­tion, for every inte­ger ‘i’, cal­cu­late x = i*i.
  4. Now with this ‘x’ there are 3 possibilities.
    1. If x == n then n is a per­fect square, return true
    2. If x > n then x has crossed the n, n is not per­fect square. Return false
    3. If above step a or b are not true then continue.

Time Com­plex­ity: O(sqrt(n))



37 is square: false
49 is square: true

You may also like...

  • lipsa patel

    How about num­ber 1? 1 is a per­fect square. The above imple­men­ta­tion will return false.