给定正整数N ,任务是检查给定数N是否可以表示为两个正理想立方体的乘积。如果可能,请打印“是” 。否则,打印“否” 。
例子:
Input: N = 216
Output: Yes
Explanation:
The given number N(= 216) can be represented as 8 * 27 = 23 * 33.
Therefore, print Yes.
Input: N = 10
Output: No
方法:解决给定问题的最简单方法是在地图中存储从1到N的立方根的所有数字的理想立方体,并检查N是否可以表示为地图中存在的两个数字的乘积。
请按照以下步骤解决问题:
- 初始化一个有序映射,例如cubes ,该映射按排序顺序存储完美的多维数据集。
- 遍历地图,检查是否存在乘积为N的对,然后打印“是” 。否则,打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if N can
// be represented as the product
// of two perfect cubes or not
void productOfTwoPerfectCubes(int N)
{
// Stores the perfect cubes
map cubes;
for (int i = 1;
i * i * i <= N; i++)
cubes[i * i * i] = i;
// Traverse the Map
for (auto itr = cubes.begin();
itr != cubes.end();
itr++) {
// Stores the first number
int firstNumber = itr->first;
if (N % itr->first == 0) {
// Stores the second number
int secondNumber = N / itr->first;
// Search the pair for the
// first number to obtain
// product N from the Map
if (cubes.find(secondNumber)
!= cubes.end()) {
cout << "Yes";
return;
}
}
}
// If N cannot be represented
// as the product of the two
// positive perfect cubes
cout << "No";
}
// Driver Code
int main()
{
int N = 216;
productOfTwoPerfectCubes(N);
return 0;
}
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the number N
// can be represented as the product
// of two perfect cubes or not
void productOfTwoPerfectCubes(int N)
{
int cube_root;
cube_root = round(cbrt(N));
// If cube of cube_root is N
if (cube_root * cube_root
* cube_root
== N) {
cout << "Yes";
return;
}
// Otherwise, print No
else {
cout << "No";
return;
}
}
// Driver Code
int main()
{
int N = 216;
productOfTwoPerfectCubes(N);
return 0;
}
Yes
时间复杂度: O(N 1/3 * log(N))
辅助空间: O(N 1/3 )
高效方法:还可以基于以下观察结果来优化上述方法:只有完美的立方体可以表示为2个完美的立方体的乘积。
Let the two numbers be x and y such that x3 * y3= N — (1)
Equation (1) can be written as:
=> (x*y)3 = N
Taking cube root both sides,
=> x*y = (N)1/3 — (2)
For equation (2) to be true, N should be a perfect cube.
因此,减少了检查N是否为理想立方体的问题。如果发现是真的,则打印“是” ,否则打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the number N
// can be represented as the product
// of two perfect cubes or not
void productOfTwoPerfectCubes(int N)
{
int cube_root;
cube_root = round(cbrt(N));
// If cube of cube_root is N
if (cube_root * cube_root
* cube_root
== N) {
cout << "Yes";
return;
}
// Otherwise, print No
else {
cout << "No";
return;
}
}
// Driver Code
int main()
{
int N = 216;
productOfTwoPerfectCubes(N);
return 0;
}
Yes
时间复杂度: O(N 1/3 )
辅助空间: O(1)