38.2k views
2 votes
Write a program that asks the user to input an integer that is a perfect square. A perfect square is an integer that is equal to the product of another integer with itself; e.g., 16 is a perfect square because it equals 4 times 4. Repeatedly force the user to input a new integer until they enter a perfect square. Once the user has entered a perfect square, print its square root as an integer. Hint: you can modulo a float by 1 to get the decimal part of the float, e.g., 2.75 % 1 equals 0.75, and 5.0 % 1 equals 0.

1 Answer

5 votes

Final answer:

A program to repeatedly ask for an integer until a perfect square is provided can be written in Python. The key is to loop asking for input, checking if the square root of the input has no decimal part. Once a perfect square is entered, its integer square root is printed.

Step-by-step explanation:

To solve the request of writing a program that asks a user to input an integer until a perfect square is entered, we can start by understanding that a perfect square is an integer that can be expressed as the product of another integer with itself. If we denote this integer as 'n', then a perfect square is n². We can find the square root of a number by raising it to the 0.5 power, which is equivalent to taking the square root function.

The program loops until a perfect square is entered. Here's the Python code:

import math
while True:
num = int(input("Enter an integer: "))
root = math.sqrt(num)
if root % 1 == 0:
print(f"The integer square root of your perfect square {num} is {int(root)}.")
break
else:
print("Please enter a perfect square.")

When the square root of the number entered has no decimal part (checked using 'root % 1 == 0'), we know that the number is a perfect square. Once a perfect square is entered, we print its square root, converting it to an integer as requested.

User Seva Parfenov
by
7.3k points