Nikhil Singhal's Blog

.Net Programming tips and gotchas

How to find if a number is perfect square

How to find if a number is perfect square

  • Comments 3

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

  • Why not use sqrt, or its iterative formula?

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

  •       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);

           }

Page 1 of 1 (3 items)
Leave a Comment
  • Please add 5 and 3 and type the answer here:
  • Post