生成排列,使得所有元素的 GCD 乘以位置不是 1
给定一个整数N ,任务是生成范围 [ 1, N ] 中数字的排列,使得:
- 所有元素的 GCD 乘以它们的位置(不是索引)大于 1
- 如果不可能返回-1。
- 如果有多种可能的排列,请打印其中任何一种。
例子:
Input: N = 8
Output: 2 1 4 3 6 5 8 7
Explanation: The elemements multiplied by their positions will be
{2*1, 1*2, 4*3, 3*4, 6*5, 5*6, 8*7, 7*8} = {2, 2, 12, 12, 30, 30, 56, 56}.
The GCD of all these numbers = 2 which is greater than 1.
Input: N = 9
Output: -1
Explanation: No permutation possible, hence return -1
方法:解决问题的思路如下:
Try to make the product of position and the number even, then in that situation GCD will be at least 2.
If there are odd number of elements then it is not possible, because odd elements are one more than possible even positions.
请按照以下步骤解决问题:
- 将所有偶数存储在一个向量中,将所有奇数存储在另一个向量中。
- 在生成排列时:
- 在偶数索引处推送偶数(即奇数位置,因为索引是基于 0 的)和
- 奇数索引处的奇数(即偶数位置)。
下面是上述方法的实现:
C++
// C++ code to implement the above approach
#include
using namespace std;
// Function to generate the permutation
vector arrangePermutation(int& N)
{
vector odd, even, res;
// If answer does not exist
if (N & 1) {
for (int i = 1; i <= N; i++) {
res.push_back(-1);
}
return res;
}
// Separately store the even numbers
// and odd numbers
for (int i = 1; i <= N; i++) {
if (i & 1) {
odd.push_back(i);
}
else {
even.push_back(i);
}
}
int k = 0, j = 0;
for (int i = 0; i < N; i++) {
// If index is even output the even
// number because, (even + 1)*even
// = even
if (i % 2 == 0) {
res.push_back(even[k++]);
}
else {
// If index is odd then output odd
// number because (odd+1)*odd = even
res.push_back(odd[j++]);
}
}
// Return the result
return res;
}
// Function to print the vector
void printResult(vector& res)
{
for (auto x : res) {
cout << x << " ";
}
cout << endl;
}
// Driver Code
int main()
{
int N = 8;
// Function call
vector res = arrangePermutation(N);
printResult(res);
return 0;
}
2 1 4 3 6 5 8 7
时间复杂度: O(N)
辅助空间: O(N)