Problem Statement

You’re given two numbers num1 and num2. You need to find the total number of perfect squares between num1 and num2.

Example 1: Let num1 = 10 and num2 = 100.

Perfect squares between 10 and 100: 16, 25, 36, 49, 64, 81, 100.

Thus, the output is 7.

Example 2: Let num1 = 15 and num2 = 82.

Perfect squares between 15 and 82: 16, 25, 36, 49, 64, 81.

Thus, the output is 6.

Example 3: Let num1 = 3 and num2 = 36.

Perfect squares between 3 and 36: 4, 9, 16, 25, 36.

Thus, the output is 5.

Basic Approach to Find the Total Number of Perfect Squares Between Two Numbers

C++ Program to Count the Total Number of Perfect Squares Between Two Numbers

Below is the C++ implementation to solve the problem:

Output:

Python Program to Count the Total Number of Perfect Squares Between Two Numbers

Next, the Python code to find the total number of perfect squares between two numbers:

Output:

JavaScript Program to Count the Total Number of Perfect Squares Between Two Numbers

Here’s how you find the total number of perfect squares between two numbers in JavaScript:

Output:

Efficient Approach to Find the Number of Perfect Squares Between Two Numbers

You can also find the total number of perfect squares between two numbers using the following formula:

The time complexity of this solution ( O(log num2) ) is better than the previous approach ( O((num2-num1) * sqrt(num2)) ).

C++ Implementation Using Efficient Formula

Below is the C++ implementation to find the total number of perfect squares between two numbers:

Output:

Python Implementation Using Efficient Formula

Below is the Python implementation to find the total number of perfect squares between two numbers:

Output:

JavaScript Implementation Using Efficient Formula

Below is the JavaScript implementation to find the total number of perfect squares between two numbers:

Output:

Monetize Your Programming Skills

Coding is considered to be one of the best career skills of the 21st century. It offers unlimited opportunities for your creative ideas that can earn you some cash. You can make money by freelancing, writing technical blogs, developing apps and APIs, selling eBooks and courses, etc. The only way you’ll discover which you like is to dive in!