In this lesson, we will find whether a given number is a perfect square or not.

We will implement several implementations of this problem and step-by-step move towards better implementations. Keep in mind we are about to dive into looking at the following perspective: how do we write a program efficiently? Hence can we improve our implementation? So let’s start!

Perfect square number

Write and run a program that takes inputs until the user enters -1 and tells whether the input number is a perfect square or not.

Sample input

25 16 23 -1

Sample output

25 is a perfect square
16 is a perfect square
23 is not a perfect square

A perfect square is a number that can be expressed as the product of an integer (let us call that number a verifier) by itself or as the second exponent of an integer. For example, 9 is a perfect square because 3×3=32=93 \times 3 = 3^2 = 9

How do we find out whether a given number is a perfect square? Just think about the following question:

For a perfect square SS, is it possible that the verifier vv is bigger then SS so that v×v=Sv \times v=S?

No vv cannot exceed SS. This means one naive idea could be to just iterate through all the possible values of v lower than or equal to SS and check if the square of vv is equal to SS.

Your task is to implement a function that checks whether the entered number is a perfect square or not. Let’s call this function isPerfectSquare(), which returns true if the parameter received is a perfect square and otherwise returns false. For example, isPerfectSquare(25) should return true and isPerfectSquare(50) should return false.

Playground for your implementation

Write down your code in the following playground:

Get hands-on with 1200+ tech skills courses.