📌  相关文章
📜  检查是否可以通过给定的运算将N转换为K的幂K

📅  最后修改于: 2021-06-26 15:32:06             🧑  作者: Mango

给定一个正数N ,我们必须查找N是否可以转换为K K的形式,其中K也是一个正整数,可以使用以下次数的次数进行运算:

  • 选择小于N当前值的任何数字,例如d。
  • N = N – d 2 ,每次改变N

如果可以用所需的形式表示数字,则打印“是”,否则打印“否”。
例子:

天真的方法:
为了解决上述问题,我们将使用递归。在每个递归步骤中,遍历N当前值的所有数字,并将其选择为d。这样,将探索所有搜索空间,如果其中任何一个N的形式为K K,则停止递归并返回true。要检查数字是否具有给定的格式,请将所有这些数字预先存储在集中。此方法采用O(D N ) ,其中D是N时间中的位数,并且可以进一步优化。

下面是给定方法的实现:

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 
using namespace std;
 
unordered_set 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 kPowKform =
       new HashSet();
  
// 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 kPowKform = new SortedSet();
     
// 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


C++
// C++ implementation to Check whether a given
// number N can be converted to the form K
// power K by the given operation
#include 
using namespace std;
 
unordered_set 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 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 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
    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


输出:
No












高效方法:
在递归方法中,我们要多次解决同一个子问题,即存在重叠子问题。因此,我们可以使用动态编程并使用缓存或存储表存储递归方法。

下面是上述方法的实现:

C++

// C++ implementation to Check whether a given
// number N can be converted to the form K
// power K by the given operation
#include 
using namespace std;
 
unordered_set 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 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 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
    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
输出:
Yes












时间复杂度: O(D * N) ,其中D是N中的位数。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。