How to find if a number is perfect square


Check out my latest post on How to find if a number is perfect square on my new blog on Programming Interviews Series.

Comments (3)

  1. Feng Yuan says:

    Why not use sqrt, or its iterative formula?

  2. Mahendra says:

    You can calculate prime factor of No. and if prime factors are even then No. is perfect square.

  3. Feng Yuan says:

          static bool IsSquareNumber(long num)

           {

               if (num < 0)

               {

                   return false;

               }

               if (num == 0)

               {

                   return true;

               }

               long s1 = -1;

               long s2 = -1;

               long s3 = 1;

               do

               {

                   s1 = s2;

                   s2 = s3;

                   s3 = (s2 + num / s2) / 2;

                   Console.WriteLine(" {0}", s3);

               }

               while (s1 != s3);

               return (s1 * s1 == num) || (s2 * s2 == num);

           }