Count of numbers in given range [L, R] that is perfect square and digits are in wave form - GeeksforGeeks

12 Jan, 2022
Given two integers L and R, the task is to count the integers in the range [L, R] such that they satisfy the following two properties:
The number must be a perfect square of any integer.
In digits of the integer must be in the wave form i.e, let d1, d2, d3, d4, d5 be the digits in the current integer, then d1 < d2 > d3 < d4... must hold true.
Examples:
Input: L = 1, R = 64Output: 7 Explanation:The special numbers in the range [1, 64] are 1, 4, 9, 16, 25, 36 and 49.
Input: L = 80, R = 82Output: 0
Naive Approach: The simplest approach to solve the problem is to traverse in the range [L, R], and for each number in the range check for the above two conditions.Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach iterate over only perfect squares and check for the second condition. Follow the steps below for the approach:
Initialize a variable say, count = 0, to count all the special numbers in the range [L, R].
Iterate over all the perfect squares that are less than R.
Define a function, say check(N), to check whether the number N satisfies the second condition by iterating over even and odd digits.
Increase the count, if the number is greater than L and function check returns true for the given number.
Finally, return the count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Utility function to check if// the digits of the current// integer forms a wave patternbool check(int N){    // Convert the number to a string    string S = to_string(N);     // Loop to iterate over digits    for (int i = 0; i < S.size(); i++) {        if (i == 0) {             // Next character of            // the number            int next = i + 1;             // Current character is            // not a local minimum            if (next < S.size()) {                if (S[i] >= S[next]) {                     return false;                }            }        }         else if (i == S.size() - 1) {             // Previous character of            // the number            int prev = i - 1;            if (prev >= 0) {                 // Character is a                // local maximum                if (i & 1) {                     // Character is not                    // a local maximum                    if (S[i] <= S[prev]) {                        return false;                    }                }                else {                    // Character is a                    // local minimum                    if (S[i] >= S[prev]) {                        return false;                    }                }            }        }        else {            int prev = i - 1;            int next = i + 1;            if (i & 1) {                 // Character is a                // local maximum                if ((S[i] > S[prev])                    && (S[i] > S[next])) {                }                else {                    return false;                }            }            else {                // Character is a                // local minimum                if ((S[i] < S[prev])                    && (S[i] < S[next])) {                }                else {                    return false;                }            }        }    }    return true;} // Function to calculate total// integer in the given rangeint totalUniqueNumber(int L, int R){    // Base case    if (R <= 0) {        return 0;    }     // Current number    int cur = 1;     // Variable to store    // total unique numbers    int count = 0;     // Iterating over perfect    // squares    while ((cur * cur) <= R) {        int num = cur * cur;         // If number is greater        // than L and satisfies        // required conditions        if (num >= L && check(num)) {            count++;        }         // Moving to the        // next number        cur++;    }     // Return Answer    return count;} // Driver Codeint main(){    int L = 1, R = 64;    cout << totalUniqueNumber(L, R);}
// Java  program for the above approachimport java.util.*;public class GFG{       // Utility function to check if  // the digits of the current  // integer forms a wave pattern  static boolean check(int N)  {         // Convert the number to a string    String S = Integer.toString(N);     // Loop to iterate over digits    for (int i = 0; i < S.length(); i++) {      if (i == 0) {         // Next character of        // the number        int next = i + 1;         // Current character is        // not a local minimum        if (next < S.length()) {          if (S.charAt(i) >= S.charAt(next)) {             return false;          }        }      }       else if (i == S.length() - 1) {         // Previous character of        // the number        int prev = i - 1;        if (prev >= 0) {           // Character is a          // local maximum          if ((i & 1) == 1) {             // Character is not            // a local maximum            if (S.charAt(i) <= S.charAt(prev)) {              return false;            }          }          else          {                         // Character is a            // local minimum            if (S.charAt(i) >= S.charAt(prev)) {              return false;            }          }        }      }      else {        int prev = i - 1;        int next = i + 1;        if ((i & 1) == 1) {           // Character is a          // local maximum          if ((S.charAt(i) > S.charAt(prev))              && (S.charAt(i) > S.charAt(next))) {          }          else {            return false;          }        }        else        {                     // Character is a          // local minimum          if ((S.charAt(i) < S.charAt(prev))              && (S.charAt(i) < S.charAt(next))) {          }          else {            return false;          }        }      }    }    return true;  }   // Function to calculate total  // integer in the given range  static int totalUniqueNumber(int L, int R)  {         // Base case    if (R <= 0) {      return 0;    }     // Current number    int cur = 1;     // Variable to store    // total unique numbers    int count = 0;     // Iterating over perfect    // squares    while ((cur * cur) <= R) {      int num = cur * cur;       // If number is greater      // than L and satisfies      // required conditions      if (num >= L && check(num)) {        count++;      }       // Moving to the      // next number      cur++;    }     // Return Answer    return count;  }   // Driver Code  public static void main(String args[])  {      int L = 1, R = 64;       // Function call      System.out.println(totalUniqueNumber(L, R));  }}// This code is contributed by Samim Hossain Mondal.
# Python  program for the above approach # Utility function to check if# the digits of the current# integer forms a wave patterndef check(N):     # Convert the number to a string    S = str(N);     # Loop to iterate over digits    for i in range(len(S)):        if (i == 0):             # Next character of            # the number            next = i + 1;             # Current character is            # not a local minimum            if (next < len(S)):                if (S[i] >= S[next]):                     return False;                         elif(i == len(S) - 1):             # Previous character of            # the number            prev = i - 1;            if (prev >= 0):                 # Character is a                # local maximum                if ((i & 1) == 1):                     # Character is not                    # a local maximum                    if (S[i] <= S[prev]):                        return False;                else:                     # Character is a                    # local minimum                    if (S[i] >= S[prev]):                        return False;                         else:            prev = i - 1;            next = i + 1;            if ((i & 1) == 1):                 # Character is a                # local maximum                if ((S[i] > S[prev]) and (S[i] > S[next])):                    return True;                else:                    return False;                             else:                 # Character is a                # local minimum                if ((S[i] < S[prev]) and (S[i] < S[next])):                    return True;                else:                    return False;                     return True; # Function to calculate total# integer in the given rangedef totalUniqueNumber(L, R):     # Base case    if (R <= 0):        return 0;         # Current number    cur = 1;     # Variable to store    # total unique numbers    count = 0;     # Iterating over perfect    # squares    while ((cur * cur) <= R):        num = cur * cur;         # If number is greater        # than L and satisfies        # required conditions        if (num >= L and check(num)):            count += 1;                 # Moving to the        # next number        cur += 1;         # Return Answer    return count; # Driver Codeif __name__ == '__main__':    L = 1;    R = 64;     # Function call    print(totalUniqueNumber(L, R)); # This code is contributed by gauravrajput1
// C# program for the above approachusing System;using System.Collections; class GFG{   // Utility function to check if  // the digits of the current  // integer forms a wave pattern  static bool check(int N)  {    // Convert the number to a string    string S = N.ToString();     // Loop to iterate over digits    for (int i = 0; i < S.Length; i++) {      if (i == 0) {         // Next character of        // the number        int next = i + 1;         // Current character is        // not a local minimum        if (next < S.Length) {          if (S[i] >= S[next]) {             return false;          }        }      }       else if (i == S.Length - 1) {         // Previous character of        // the number        int prev = i - 1;        if (prev >= 0) {           // Character is a          // local maximum          if ((i & 1) == 1) {             // Character is not            // a local maximum            if (S[i] <= S[prev]) {              return false;            }          }          else {            // Character is a            // local minimum            if (S[i] >= S[prev]) {              return false;            }          }        }      }      else {        int prev = i - 1;        int next = i + 1;        if ((i & 1) == 1) {           // Character is a          // local maximum          if ((S[i] > S[prev])              && (S[i] > S[next])) {          }          else {            return false;          }        }        else {          // Character is a          // local minimum          if ((S[i] < S[prev])              && (S[i] < S[next])) {          }          else {            return false;          }        }      }    }    return true;  }   // Function to calculate total  // integer in the given range  static int totalUniqueNumber(int L, int R)  {    // Base case    if (R <= 0) {      return 0;    }     // Current number    int cur = 1;     // Variable to store    // total unique numbers    int count = 0;     // Iterating over perfect    // squares    while ((cur * cur) <= R) {      int num = cur * cur;       // If number is greater      // than L and satisfies      // required conditions      if (num >= L && check(num)) {        count++;      }       // Moving to the      // next number      cur++;    }     // Return Answer    return count;  }    // Driver Code  public static void Main()  {    int L = 1, R = 64;     // Function call    Console.Write(totalUniqueNumber(L, R));   }}// This code is contributed by Samim Hossain Mondal.
<script>       // JavaScript code for the above approach        // Utility function to check if       // the digits of the current       // integer forms a wave pattern       function check(N)       {                   // Convert the number to a string           let S = N.toString();            // Loop to iterate over digits           for (let i = 0; i < S.length; i++) {               if (i == 0) {                    // Next character of                   // the number                   let next = i + 1;                    // Current character is                   // not a local minimum                   if (next < S.length) {                       if (S[i] >= S[next]) {                            return false;                       }                   }               }                else if (i == S.length - 1) {                    // Previous character of                   // the number                   let prev = i - 1;                   if (prev >= 0) {                        // Character is a                       // local maximum                       if (i & 1) {                            // Character is not                           // a local maximum                           if (S[i] <= S[prev]) {                               return false;                           }                       }                       else {                           // Character is a                           // local minimum                           if (S[i] >= S[prev]) {                               return false;                           }                       }                   }               }               else {                   let prev = i - 1;                   let next = i + 1;                   if (i & 1) {                        // Character is a                       // local maximum                       if ((S[i] > S[prev])                           && (S[i] > S[next])) {                       }                       else {                           return false;                       }                   }                   else {                       // Character is a                       // local minimum                       if ((S[i] < S[prev])                           && (S[i] < S[next])) {                       }                       else {                           return false;                       }                   }               }           }           return true;       }        // Function to calculate total       // integer in the given range       function totalUniqueNumber(L, R) {           // Base case           if (R <= 0) {               return 0;           }            // Current number           let cur = 1;            // Variable to store           // total unique numbers           let count = 0;            // Iterating over perfect           // squares           while ((cur * cur) <= R) {               let num = cur * cur;                // If number is greater               // than L and satisfies               // required conditions               if (num >= L && check(num)) {                   count++;               }                // Moving to the               // next number               cur++;           }            // Return Answer           return count;       }        // Driver Code       let L = 1, R = 64;       document.write(totalUniqueNumber(L, R));  // This code is contributed by Potta Lokesh   </script>
  
7
Time Complexity: O(sqrt(N))Auxiliary Space: O(1) 
lokeshpotta20
samim2000
GauravRajput1
array-range-queries
Maths
number-digits
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to convert a given number to words
Modular multiplicative inverse
Algorithm to solve Rubik's Cube
Program to multiply two matrices
Count ways to reach the n'th stair
Program to print prime numbers from 1 to N.
Check if a number is Palindrome
Singular Value Decomposition (SVD)
Fizz Buzz Implementation
Program for Armstrong Numbers