Skip to content
Related Articles

Related Articles

Check if N can be converted to the form K power K by the given operation
  • Last Updated : 22 Oct, 2020

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 the 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++14




// C++ 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;
}

Java




// 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

Python3




# 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

C#




// C# implementation to check whether a given
// number N can be converted to the form K
// power K by the given operation
using System;
using System.Collections.Generic;
 
class GFG{
     
static SortedSet<int> kPowKform = new SortedSet<int>();
     
// 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)
        Console.Write("Yes");
    else
        Console.Write("No");
}
     
// Driver code
public static void 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.Add(val);
    }
    canBeConverted(N);
}
}
 
// This code is contributed by sanjoy_62
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 memorize the recursive approach using a cache or memorization table.

Below is the implementation of the above approach:

C++




// C++ 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;
}

Java




// 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<>();
static int []dp = new int[100005];
 
// Function to check if
// a number is converatable
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;
   
  // 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) != 0)
      {
        answer = 1;
        break;
      }
    }
 
    // Reduce the number
    // each time
    x /= 10;
  }
 
  // Store and return the
  // answer to this subproblem
  return dp[n] = answer;
}
 
// Function to check the above method
static void canBeConverted(int n)
{
  // Initialise the dp table
  for (int i = 0; i < n; i++)
    dp[i] = -1;
 
  // Check if conversion if possible
  if (func(n) == 0)
    System.out.print("Yes");
  else
    System.out.print("No");
}
 
// Driver code
public static void main(String[] args)
{
  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.add(val);
  }
  canBeConverted(N);
}
}
 
// This code is contributed by Rajput-Ji

Python3




# 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, dp):
     
    global kPowKform
    if (n <= 0):
        return 0
 
    # Check if n is of the form k^k
    if (n in kPowKform):
        return 1
         
    if (dp[n] != -1):
        return dp[n]
         
    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, dp)):
                answer = 1
                break
 
        # Reduce the number each time
        x //= 10
          
    dp[n] = answer
     
    # Return the result
    return answer
 
# Function to check the above method
def canBeConverted(n):
     
    dp = [-1 for i in range(10001)]
     
    # Check if conversion if possible
    if (func(n, dp)):
        print("Yes")
    else:
        print("No")
 
# Driver code
if __name__ == '__main__':
     
    N = 13
 
    # 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 grand_master

C#




// C# implementation to check whether a given
// number N can be converted to the form K
// power K by the given operation
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
   
static HashSet<int> kPowKform = new HashSet<int>();
static int []dp = new int[100005];
  
// Function to check if a number
// is converatable
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;
  
    // 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) != 0)
            {
                answer = 1;
                break;
            }
        }
  
        // Reduce the number each time
        x /= 10;
    }
  
    // Store and return the
    // answer to this subproblem
    dp[n] = answer;
    return answer;
}
  
// Fcuntion to check the above method
static void canBeConverted(int n)
{
     
    // Initialise the dp table
    Array.Fill(dp, -1);
  
    // Check if conversion if possible
    if (func(n) != 0)
        Console.Write("Yes");
    else
        Console.Write("No");
}
 
// Driver code
public static void Main(string[] args)
{
   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.Add(val);
    }
    canBeConverted(N);
}
}
 
// This code is contributed by rutvik_56
Output: 
Yes












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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :