Check whether the given number is a perfect square

Objec­tive:  Given an integer check whether it is a perfect square.

Example:

number = 37
Output: false

number = 49
Output: true

This is fun puzzle which is asked in the interview.
Approach:

  1. Say number is n.
  2. Start a loop from 1 to n/2.
  3. During iteration, for every integer ‘i’, calculate x = i*i.
  4. Now with this ‘x’ there are 3 possibilities.
    1. If x == n then n is a perfect square, return true
    2. If x > n then x has crossed the n, n is not perfect square. Return false
    3. If above step a or b are not true then continue.

Time Complexity: O(sqrt(n))

Code:


Output:

37 is square: false
49 is square: true

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

  • lipsa patel

    How about number 1? 1 is a perfect square. The above implementation will return false.

%d bloggers like this: