Count integers whose square lie in given range and digits are perfect square
Given two integers L and R. Then the task is to output the count of integers X, such that L ≤ X2 ≤ R and X2 only consist of digits, which are perfect squares.
Examples:
Input: L = 167, R = 456
Output: 2
Explanation: Two numbers are 20 and 21, Their squares are 400 and 441 respectively. It can be verified that squares of both 20 and 21 are in the range of L and R and contains only digits which are square numbers. ie. 0, 4, 1.Input: L = 4567, R = 78990
Output: 11
Approach: Implement the idea below to solve the problem
Find the nearest numbers from L and R both using floor(), ceil(), and in-built sqrt() function. Traverse all the integer values between those obtained two numbers and check if a number exists such that they only contain digits 0, 1, 4, 9, or not. Count those numbers in a variable.
Steps were taken to solve the problem:
- Initialize a variable ans = 0, to store the count of perfect square occurrences.
- Take an integer variable X, Which will be the perfect square nearest to R and can be obtained as X = (Math.floor(Math.sqrt(R))).
- Take an integer variable Y, Which will be the nearest perfect square number to L and can be obtained as (Math.floor(Math.sqrt(L))).
- Traverse all the integer values between X and Y using Loop and check:
- How many numbers are there such that, They only contain 0, 1, 4, and 9 as their digits?
- If all digits are only 0, 1, 4, or 9, then increment the ans by 1.
- Return the ans.
Below is the implementation of the above approach.
Java
// Java code to implement the approach import java.io.*;import java.lang.*;import java.util.*; // Name of the class has to be "GFG"// only if the class is public.class GFG { // Driver code public static void main(String[] args) { // Input values X and Y long X = 167; long Y = 456; // Function call System.out.println(countSquare(X, Y)); } // Function to count the number of valid X static long countSquare(long X, long Y) { // Finding nearest integers such // that there squares are in range // of L and R(both inclusive) Y = (long)(Math.floor(Math.sqrt(Y))); X = (long)(Math.ceil(Math.sqrt(X))); // Variable to store answer or // count of required numbers long ans = 0; // Traversing from nearest X to Y while (X <= Y) { long k = X * X; // Intialise flag to check // which digit is present boolean flag = true; // Checking that square of // current number consists only // digits 0, 1, 4, 9 or not while (k > 0) { long rem = k % 10; // If any other digit is // present flag = false if (!(rem == 0 || rem == 1 || rem == 4 || rem == 9)) { flag = false; break; } k /= 10; } if (flag) { // Incrementing count // variable ans++; } // Incrementing value of X X++; } // Return maximum count of // numbers obtained return ans; }} |
2
Time Complexity: O(sqrt(R))
Auxiliary Space: O(1)
Related Articles:





Please Login to comment...