给定两个整数N和K ,任务是检查在对K进行相加或相减后, N是否可以制成一个完美的立方体。
例子:
Input: N = 7, K = 1
Output: Yes
7 + 1 = 8 which is a perfect cube (23 = 8)
Input: N = 5, K = 4
Output: Yes
5 – 4 = 1 which is a perfect cube (13 = 1)
方法:解决此问题的最简单方法是检查(N + K)或(N – K)是否是理想的立方体。
- 检查(N + K)是否是理想的立方体
- 如果不是,则检查(N – K)是否为理想的立方体。
- 如果两者都不是理想的立方体,则打印“否”,否则打印“是”。
- 为了检查一个数字是否是一个完美的立方体,最简单的方法是找到该数字的立方根底值的立方体,然后检查该立方体是否与该数字相同。
if(N3 == (floor(∛N))3)
Then N is a perfect cube
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to check if a number is
// a perfect Cube or not
bool isPerfectCube(int x)
{
int cr = round(cbrt(x));
return (cr * cr * cr == x);
}
void canBePerfectCube(int N, int K)
{
if (isPerfectCube(N + K)
|| isPerfectCube(N - K))
cout << "Yes\n";
else
cout << "No\n";
}
// Driver code
int main()
{
int N = 7, K = 1;
canBePerfectCube(N, K);
N = 5, K = 4;
canBePerfectCube(N, K);
N = 7, K = 2;
canBePerfectCube(N, K);
return 0;
}
Java
// Java implementation of the above approach
class GFG {
// Function to check if a number is
// a perfect Cube or not
static boolean isPerfectCube(int x)
{
int cr = (int)Math.cbrt(x);
return (cr * cr * cr == x);
}
static void canBePerfectCube(int N, int K)
{
if (isPerfectCube(N + K)
|| isPerfectCube(N - K) == true)
System.out.println("Yes");
else
System.out.println("No");
}
// Driver code
public static void main (String[] args)
{
int N = 7;
int K = 1;
canBePerfectCube(N, K);
N = 5;
K = 4;
canBePerfectCube(N, K);
N = 7; K = 2;
canBePerfectCube(N, K);
}
}
// This code is contributed by Yash_R
Python3
# Python3 implementation of the above approach
# Function to check if a number is
# a perfect Cube or not
def isPerfectCube(x) :
cr = int(x ** (1/3));
return (cr * cr * cr == x);
def canBePerfectCube(N, K) :
if (isPerfectCube(N + K) or isPerfectCube(N - K)) :
print("Yes");
else :
print("No");
# Driver code
if __name__ == "__main__" :
N = 7; K = 1;
canBePerfectCube(N, K);
N = 5; K = 4;
canBePerfectCube(N, K);
N = 7; K = 2;
canBePerfectCube(N, K);
# This code is contributed by Yash_R
C#
// C# implementation of the above approach
using System;
class GFG {
// Function to check if a number is
// a perfect Cube or not
static bool isPerfectCube(int x)
{
int cr = (int)Math.Cbrt(x);
return (cr * cr * cr == x);
}
static void canBePerfectCube(int N, int K)
{
if (isPerfectCube(N + K)
|| isPerfectCube(N - K) == true)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
// Driver code
public static void Main (string[] args)
{
int N = 7;
int K = 1;
canBePerfectCube(N, K);
N = 5;
K = 4;
canBePerfectCube(N, K);
N = 7; K = 2;
canBePerfectCube(N, K);
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
Yes
Yes
No