70,279 views
18 votes
18 votes
Write a program that accepts a positive integer N as command-line argument, and outputs True if N is the square of some integer, and False otherwise. Do not use math.sqrt() or similar! Hint: Clearly, all candidates i which may satisfy i2 = N must be at most N (for which "corner case" of N is i equal to N?). Therefore, it is sufficient to check if there exists an i in the range 1 ≤ i ≤ N such that i2 = N. In other words, you want to evaluate the expression (12 == N)or (22 == N)or (32 == N)or ··· or ((N − 1)2 == N) or (N2 == N). Practice goal: A variation of the primality checking program we have seen in class; follows a Boolean accumulation pattern, with logical or.

User Alexander Clark
by
2.4k points

1 Answer

26 votes
26 votes

Answer:

In Python:

N = int(input("Positive integer: "))

if N > 0:

flag = False

for i in range(1,N+1):

if i * i == N:

flag = True

break

print(str(flag))

else:

print("Positive integer only")

Step-by-step explanation:

N = int(input("Positive integer: "))

If the number is positive

if N > 0:

This initializes a boolean variable to false

flag = False

This iterates from 1 to the input integer

for i in range(1,N+1):

This checks if th number is a square of some integer

if i * i == N:

If yes, flag is set to true

flag = True

The loop is exited

break

This prints either true or false, depending on the result of the loop

print(str(flag))

If otherwise, that the number is not positive

else:

print("Positive integer only")

User JKnight
by
2.9k points