Check if N can be converted to the form K power K by the given operation

Given a positive number N, we have to find whether N can be converted to the form KK where K is also a positive integer, using the following operation any number of times :

  • Choose any digit less than the current value of N, say d.
  • N = N – d2, change N each time

If it is possible to express the number in required form then print “Yes” otherwise print “No”.

Examples:

Input: N = 13
Output: Yes
Explanation:
For integer 13 choose d = 3 : N = 13 – 32 = 4, 4 is of the form 22. Hence, the output is 4.

Input: N = 90
Output: No
Explanation:
It is not possible to express the number 90 in required form.



Naive Approach:

To solve the problem mentioned above we will use Recursion. In each recursive step, traverse through all the digits of the current value of N, and choose it as d. This way all the search spaces will be explored and if in any of them N comes out to be of the form KK stop the recursion and return true. To check whether the number is of the given form, pre-store all such numbers in a set. This method takes O(DN), where D is the number of digits in N time and can be further optimized.

Below is the implementation of the given approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation to Check whether a given
// number N can be converted to the form K
// power K by the given operation
#include <bits/stdc++.h>
using namespace std;
  
unordered_set<int> kPowKform;
  
// Function to check if N can
// be converted to K power K
int func(int n)
{
    if (n <= 0)
        return 0;
  
    // Check if n is of the form k^k
    if (kPowKform.count(n))
        return 1;
  
    int answer = 0;
    int x = n;
  
    // Iterate through each digit of n
    while (x > 0) {
        int d = x % 10;
  
        if (d != 0) {
            // Check if it is possible to
            // obtain number of given form
            if (func(n - d * d)) {
                answer = 1;
                break;
            }
        }
  
        // Reduce the number each time
        x /= 10;
    }
  
    // Return the result
    return answer;
}
  
// Function to check the above method
void canBeConverted(int n)
{
  
    // Check if conversion if possible
    if (func(n))
        cout << "Yes";
  
    else
        cout << "No";
}
  
// Driver code
int main()
{
    int N = 90;
  
    // Pre store K power K form of numbers
    // Loop till 8, becasue 8^8 > 10^7
  
    for (int i = 1; i <= 8; i++) {
        int val = 1;
        for (int j = 1; j <= i; j++)
            val *= i;
  
        kPowKform.insert(val);
    }
  
    canBeConverted(N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA implementation to Check whether a given
// number N can be converted to the form K
// power K by the given operation
  
import java.util.*;
  
class GFG{
   
static HashSet<Integer> kPowKform = new HashSet<Integer>();
   
// Function to check if N can
// be converted to K power K
static int func(int n)
{
    if (n <= 0)
        return 0;
   
    // Check if n is of the form k^k
    if (kPowKform.contains(n))
        return 1;
   
    int answer = 0;
    int x = n;
   
    // Iterate through each digit of n
    while (x > 0) {
        int d = x % 10;
   
        if (d != 0) {
            // Check if it is possible to
            // obtain number of given form
            if (func(n - d * d)==1) {
                answer = 1;
                break;
            }
        }
   
        // Reduce the number each time
        x /= 10;
    }
   
    // Return the result
    return answer;
}
   
// Function to check the above method
static void canBeConverted(int n)
{
   
    // Check if conversion if possible
    if (func(n)==1)
        System.out.print("Yes");
   
    else
        System.out.print("No");
}
   
// Driver code
public static void main(String[] args)
{
    int N = 90;
   
    // Pre store K power K form of numbers
    // Loop till 8, becasue 8^8 > 10^7
   
    for (int i = 1; i <= 8; i++) {
        int val = 1;
        for (int j = 1; j <= i; j++)
            val *= i;
   
        kPowKform.add(val);
    }
   
    canBeConverted(N);
   
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to Check whether a given
# number N can be converted to the form K
# power K by the given operation
  
kPowKform=dict()
  
# Function to check if N can
# be converted to K power K
def func(n):
    global kPowKform
    if (n <= 0):
        return 0
  
    # Check if n is of the form k^k
    if (n in kPowKform):
        return 1
  
    answer = 0
    x = n
  
    # Iterate through each digit of n
    while (x > 0):
        d = x % 10
  
        if (d != 0):
            # Check if it is possible to
            # obtain number of given form
            if (func(n - d * d)):
                answer = 1
                break
  
  
        # Reduce the number each time
        x //= 10
  
    # Return the result
    return answer
  
# Function to check the above method
def canBeConverted(n):
  
    # Check if conversion if possible
    if (func(n)):
        print("Yes")
  
    else:
        print("No")
  
# Driver code
if __name__ == '__main__':
    N = 90
  
    # Pre store K power K form of numbers
    # Loop till 8, becasue 8^8 > 10^7
  
    for i in range(1,9):
        val = 1
        for j in range(1,i+1):
            val *= i
  
        kPowKform[val]=1
  
  
    canBeConverted(N)
  
# This code is contributed by mohit kumar 29    

chevron_right


Output:

No

Efficient Approach:

In the recursive approach, we are solving the same subproblem multiple times i.e there are Overlapping Subproblems. So we can use Dynamic Programming and memoize the recursive approach using a cache or memorization table.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation to Check whether a given
// number N can be converted to the form K
// power K by the given operation
#include <bits/stdc++.h>
using namespace std;
  
unordered_set<int> kPowKform;
int dp[100005];
  
// Function to check if a number is converatable
int func(int n)
{
    if (n <= 0)
        return 0;
  
    // Check if n is of the form k^k
    if (kPowKform.count(n))
        return 1;
  
    // Check if the subproblem has been solved before
    if (dp[n] != -1)
        return dp[n];
  
    int answer = 0;
    int x = n;
  
    // Iterate through each digit of n
    while (x > 0) {
        int d = x % 10;
        if (d != 0) {
            // Check if it is possible to
            // obtain numebr of given form
            if (func(n - d * d)) {
                answer = 1;
                break;
            }
        }
  
        // Reduce the number each time
        x /= 10;
    }
  
    // Store and return the
    // answer to this subproblem
    return dp[n] = answer;
}
  
// Fcuntion to check the above method
void canBeConverted(int n)
{
  
    // Initialise the dp table
    memset(dp, -1, sizeof(dp));
  
    // Check if conversion if possible
    if (func(n))
        cout << "Yes";
  
    else
        cout << "No";
}
  
// Driver code
int main()
{
    int N = 13;
  
    // Pre store K power K form of numbers
    // Loop till 8, becasue 8^8 > 10^7
    for (int i = 1; i <= 8; i++) {
        int val = 1;
  
        for (int j = 1; j <= i; j++)
            val *= i;
  
        kPowKform.insert(val);
    }
  
    canBeConverted(N);
  
    return 0;
}

chevron_right


Output:

Yes

Time Complexity: O(D * N), where D is the number of digits in N.

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29, Rajput-Ji