用 C++ 找到滿足給定條件的第一個 N 個自然數的排列


假設我們有兩個整數 N 和 K,並且我們必須找到第一個 N 個自然數的排列 P,使得對於所有 1 <= i <= N,恰好有 K 個元素滿足條件 GCD(P[i], i) > 1。因此,當 N = 3 和 K = 1 時,輸出將為 2、1、3。並且 gcd(2, 1) = 1,gcd(1, 2) = 1,gcd(3, 3) = 3

方法很簡單,我們將保持最後 k 個元素的位置,移動其餘元素,這樣第 i 個元素將放置在 (i + 1) 位置,並且 (N - K) 位置將保持在位置 1,因為 gcd(x,x+1) = 1。

示例

 即時演示

#include<iostream>
using namespace std;
void findPermutation(int n, int k) {
   int permutation[n + 1];
   for (int i = 1; i <= n; i++)
   permutation[i] = i;
   for (int i = 1; i < n - k; i++)
   permutation[i + 1] = i;
   permutation[1] = n - k;
   for (int i = 1; i <= n; i++)
   cout << permutation[i] << " ";
}
int main() {
   int n = 5, k = 2;
   cout << "The permutation is: ";
   findPermutation(n, k);
}

輸出

The permutation is: 3 1 2 4 5

更新時間:2019 年 12 月 18 日

179 瀏覽

開啟您的 職業生涯

完成課程即可獲得證書

開始學習
廣告
© . All rights reserved.