Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to check perfect Square? [duplicate]

Tags:

c#

square-root

Possible Duplicate:
What's a good algorithm to determine if an input is a perfect square?

I want Shortest and Simplest way to Check a number is perfect square in C#

Some of Perfect Squares:

1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ...... 
like image 262
Javed Akram Avatar asked Feb 03 '11 12:02

Javed Akram


People also ask

What is the quickest way to determine if a number is a perfect square?

You can also tell if a number is a perfect square by finding its square roots. Finding the square root is the inverse (opposite) of squaring a number. If you find the square root of a number and it's a whole integer, that tells you that the number is a perfect square. For instance, the square root of 25 is 5.

How do you check if a number is a perfect square C#?

double result = Math. Sqrt(numberToCheck); bool isSquare = result%1 == 0; isSquare should now be true for all squares, and false for all others.


1 Answers

Probably checking if the square root of the number has any decimal part, or if it is a whole number.

Implementationwise, I would consider something like this:

double result = Math.Sqrt(numberToCheck); bool isSquare = result%1 == 0; 

isSquare should now be true for all squares, and false for all others.

like image 144
Øyvind Bråthen Avatar answered Sep 20 '22 21:09

Øyvind Bråthen