Problem Solving: Perfect Square Numbers
Learn to write a program that takes a stream of numbers and prints them whether a number is a complete square or not.
We'll cover the following
- Perfect square number
- Complete implementation
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
How do we find out whether a given number is a perfect square? Just think about the following question:
For a perfect square , is it possible that the verifier is bigger then so that ?
No cannot exceed . This means one naive idea could be to just iterate through all the possible values of v lower than or equal to and check if the square of is equal to .
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.