Felix
Felix

Reputation: 61

How can I test if a number is a square number in Python?

My code is

if graph == square_grid and type(math.sqrt(nodes)) is not int: 
    print "Your netork can't have that number of nodes" 

Of course this doesn't work because math.sqrt always returns a float. How can I do this?

Upvotes: 4

Views: 1219

Answers (4)

s3dev
s3dev

Reputation: 9681

Using pure maths (no libraries) a square number can be determined in Python as follows:

not n**0.5 % 1

As the square root of a square integer is an integer, this test uses modulo 1 equal to zero to test if the square root is an integer.

For example:

The following will print the first five square numbers:

for i in range(1, 26):
    if not i**0.5 % 1:
        print(i)

Output:

1
4
9
16
25

Upvotes: 0

Christian Geier
Christian Geier

Reputation: 2149

try:

math.sqrt(nodes) == int(math.sqrt(nodes))

Upvotes: 1

Ryan Saxe
Ryan Saxe

Reputation: 17829

Because math.sqrt always returns a float, you can use the built in is_integer method

def is_square(x):
    answer = math.sqrt(x)
    return answer.is_integer()

this will return True if x is a square and False if it's not

>>> is_square(25)
True
>>> is_square(14)
False

Upvotes: 7

Fred Foo
Fred Foo

Reputation: 363527

One way is

int(math.sqrt(x)) ** 2 == x

Upvotes: 13

Related Questions