Open In App

Count integers whose square lie in given range and digits are perfect square

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

C++




// C++ implementation
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of valid X
long countSquare(long X, long Y)
{
   
  // Finding nearest integers such
  // that  their squares are in range
  // of L and R(both inclusive)
  Y = (int)sqrt(Y);
  X = ceil(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;
 
    // Initialise flag to check
    // which digit is present
    bool 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;
}
 
int main()
{
 
  // Driver code
 
  // Input values X and Y
  long X = 167;
  long Y = 456;
 
  // Function call
  cout << (countSquare(X, Y));
 
  return 0;
}
 
// This code is contributed by ksam24000


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  their 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;
 
            // Initialise 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;
    }
}


Python3




# Python implementation of the approach
import math
 
# Function to count the number of valid X
def countSquare(X, Y):
 
    # Finding nearest integers such
    # that  their squares are in range
    # of L and R(both inclusive)
    Y = int(math.sqrt(Y))
    X = math.ceil(math.sqrt(X))
 
    # Variable to store answer or
    # count of required numbers
    ans = 0
 
    # Traversing from nearest X to Y
    while (X <= Y):
 
        k = X * X
 
        # Initialise flag to check
        # which digit is present
        flag = True
 
        # Checking that square of
        # current number consists only
        # digits 0, 1, 4, 9 or not
        while (k > 0):
 
            rem = k % 10
 
            # If any other digit is
            # present flag = false
            if (not(rem == 0 or rem == 1 or rem == 4 or rem == 9)):
                flag = False
                break
 
            k //= 10
 
        if (flag):
 
            # Incrementing count
            # variable
            ans += 1
 
        # Incrementing value of X
        X += 1
 
    # Return maximum count of
    # numbers obtained
    return ans
 
# Driver code
 
# Input values X and Y
X = 167
Y = 456
 
# Function call
print(countSquare(X, Y))
 
# This code is contributed by Tapesh(tapeshdua420)


C#




// C# program for above approach
using System;
 
class GFG
{
 
  // Function to count the number of valid X
  static long countSquare(long X, long Y)
  {
    // Finding nearest integers such
    // that  their squares are in range
    // of L and R(both inclusive)
    Y = (long)(Math.Floor(Math.Sqrt(Y)));
    X = (long)(Math.Ceiling(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;
 
      // Initialise flag to check
      // which digit is present
      bool 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;
  }
 
  // Driver Code
  public static void Main()
  {
    // Input values X and Y
    long X = 167;
    long Y = 456;
 
    // Function call
    Console.Write(countSquare(X, Y));
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




// Javascript implementation of the approach
function countSquare(X, Y) {
    // Finding nearest integers such
    // that  their squares are in range
    // of L and R(both inclusive)
    Y = Math.floor(Math.sqrt(Y));
    X = Math.ceil(Math.sqrt(X));
 
    // Variable to store answer or
    // count of required numbers
    var ans = 0;
 
    // Traversing from nearest X to Y
    while (X <= Y) {
        var k = X * X;
 
        // Initialise flag to check
        // which digit is present
        var flag = true;
 
        // Checking that square of
        // current number consists only
        // digits 0, 1, 4, 9 or not
        while (k > 0) {
            var rem = k % 10;
 
            // If any other digit is
            // present flag = false
            if (!(rem == 0 || rem == 1 || rem == 4 || rem == 9)) {
                flag = false;
                break;
            }
 
            k = Math.floor(k / 10);
        }
 
        if (flag) {
            // Incrementing count
            // variable
            ans += 1;
        }
 
        // Incrementing value of X
        X += 1;
    }
 
    // Return maximum count of
    // numbers obtained
    return ans;
}
 
// Driver code
 
// Input values X and Y
var X = 167;
var Y = 456;
 
// Function call
console.log(countSquare(X, Y));
 
// This code is contributed by Tapesh(tapeshdua420)


Output

2



Time Complexity: O(sqrt(R))
Auxiliary Space: O(1)

Another Approach:

  1. Define a function “containsOnly0149” that takes an integer as input and returns true if it contains only digits 0, 1, 4, and 9.a. Loop through the digits of the input integer by dividing it by 10 until the integer becomes 0.
    b. If any digit is not 0, 1, 4, or 9, return false.
    c. If all digits are 0, 1, 4, or 9, return true.
  2. Define a function “countSquare” that takes two long integers X and Y as input and returns the number of perfect squares between X and Y (both inclusive) that contain only digits 0, 1, 4, and 9.
    a. Initialize a long integer variable “ans” to 0.
    b. Loop through all possible squares between 0 and the square root of Y.
    i. Calculate the square of the loop variable.
    ii. If the square is between X and Y and contains only digits 0, 1, 4, and 9, increment the “ans” variable.
    c. Return the “ans” variable.
  3. In the main function, define two long integer variables X and Y.
  4. Call the “countSquare” function with X and Y as input and print the result.

Below is the implementation of the above approach:

C++




// This program counts the number of perfect squares between
// given range X and Y whose digits are all 0, 1, 4 or 9.
 
#include <iostream>
using namespace std;
 
// Function to check if a number contains only digits 0, 1,
// 4 or 9.
bool containsOnly0149(int n)
{
    while (n > 0) {
        int digit = n % 10;
        if (digit != 0 && digit != 1 && digit != 4
            && digit != 9) {
            return false;
        }
        n /= 10;
    }
    return true;
}
 
// Function to count the number of valid squares between X
// and Y.
long countSquare(long X, long Y)
{
    long ans = 0;
    for (long i = 0; i * i <= Y; i++) {
        long k = i * i;
        if (k >= X && containsOnly0149(k)) {
            ans++;
        }
    }
    return ans;
}
 
// Main function to take input and call the countSquare()
// function.
int main()
{
    long X = 167;
    long Y = 456;
    cout << countSquare(X, Y) << endl;
    return 0;
}
// This code is contributed by rudra1807raj


Java




public class GFG {
 
    // Function to check if a number contains only digits 0,
    // 1, 4 or 9.
    static boolean containsOnly0149(long n)
    {
        while (n > 0) {
            long digit = n % 10;
            if (digit != 0 && digit != 1 && digit != 4
                && digit != 9) {
                return false;
            }
            n /= 10;
        }
        return true;
    }
 
    // Function to count the number of valid squares between
    // X and Y.
    static long countSquare(long X, long Y)
    {
        long ans = 0;
        for (long i = 0; i * i <= Y; i++) {
            long k = i * i;
            if (k >= X && containsOnly0149(k)) {
                ans++;
            }
        }
        return ans;
    }
 
    // Main function to call the countSquare() function.
    public static void main(String[] args)
    {
        long X = 167;
        long Y = 456;
        System.out.println(countSquare(X, Y));
    }
}


Python3




# This program counts the number of perfect squares between
# given range X and Y whose digits are all 0, 1, 4 or 9.
 
# Function to check if a number contains only digits 0, 1,
# 4 or 9.
def containsOnly0149(n):
    while n > 0:
        digit = n % 10
        if digit != 0 and digit != 1 and digit != 4 and digit != 9:
            return False
        n //= 10
    return True
 
# Function to count the number of valid squares between X
# and Y.
def countSquare(X, Y):
    ans = 0
    i = 0
    while i * i <= Y:
        k = i * i
        if k >= X and containsOnly0149(k):
            ans += 1
        i += 1
    return ans
 
# Main function to take input and call the countSquare()
# function.
def main():
    X = 167
    Y = 456
    print(countSquare(X, Y))
 
if __name__ == '__main__':
    main()


C#




using System;
 
public class GFG {
    // Function to check if a number contains only digits 0,
    // 1, 4, or 9
    public static bool ContainsOnly0149(long n)
    {
        while (n > 0) {
            long digit = n % 10;
            if (digit != 0 && digit != 1 && digit != 4
                && digit != 9) {
                return false;
            }
            n /= 10;
        }
        return true;
    }
 
    // Function to count the number of valid squares between
    // X and Y.
    public static long CountSquare(long X, long Y)
    {
        long ans = 0;
        for (long i = 0; i * i <= Y; i++) {
            long k = i * i;
            if (k >= X && ContainsOnly0149(k)) {
                ans++;
            }
        }
        return ans;
    }
 
    // Main function to take input and call the
    // CountSquare() function.
    public static void Main()
    {
        long X = 167;
        long Y = 456;
        Console.WriteLine(CountSquare(X, Y));
    }
}


Javascript




// This program counts the number of perfect squares between
// given range X and Y whose digits are all 0, 1, 4 or 9.
 
// Function to check if a number contains only digits 0, 1,
// 4 or 9.
function containsOnly0149(n) {
    while (n > 0) {
        let digit = n % 10;
        if (digit != 0 && digit != 1 && digit != 4 && digit != 9) {
            return false;
        }
        n = Math.floor(n / 10);
    }
    return true;
}
 
// Function to count the number of valid squares between X
// and Y.
function countSquare(X, Y) {
    let ans = 0;
    for (let i = 0; i * i <= Y; i++) {
        let k = i * i;
        if (k >= X && containsOnly0149(k)) {
            ans++;
        }
    }
    return ans;
}
 
// Main function to take input and call the countSquare()
// function.
let X = 167;
let Y = 456;
console.log(countSquare(X, Y));


Output:

2

Time Complexity: The time complexity of the countSquare function is O(sqrt(Y)), as it loops through all possible squares from 0 to sqrt(Y) and checks if each square contains only digits 0, 1, 4, and 9.

Auxiliary Space: The space complexity of the function is O(1), as it only uses a few variables to store the count and loop indices, and does not create any data structures that grow with the input size.

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads