從 C++ 中每一對 gcd() 找到原始數字


概念

關於給定陣列 array[],其中包含另一個數組所有可能元素對的 GCD,我們的任務是確定用於計算 GCD 陣列的原始數字。

輸入

array[] = {6, 1, 1, 13}

輸出

13 6
gcd(13, 13) = 13
gcd(13, 6) = 1
gcd(6, 13) = 1
gcd(6, 6) = 6

輸入

arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 6, 6, 8, 11, 13, 3, 3}

輸出

13 11 8 6 6

方法

  • 首先,按降序對陣列排序。

  • 最大元素始終是原始數字之一。保留該數字並將其從陣列中刪除。

  • 從最大值開始,計算步驟中選取的元素和當前元素的 GCD,並從給定陣列中丟棄 GCD 值。

示例

 現場演示

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Shows utility function to print
// the contents of an array
void printArr(int array[], int n1){
   for (int i = 0; i < n1; i++)
      cout << array[i] << " ";
}
// Shows function to determine the required numbers
void findNumbers(int array[], int n1){
   // Used to sort array in decreasing order
   sort(array, array + n1, greater<int>());
   int freq1[array[0] + 1] = { 0 };
   // Here, count frequency of each element
   for (int i = 0; i < n1; i++)
      freq1[array[i]]++;
   // Shows size of the resultant array
   int size1 = sqrt(n1);
   int brr1[size1] = { 0 }, x1, l1 = 0;
   for (int i = 0; i < n1; i++) {
      if (freq1[array[i]] > 0) {
         // Here, store the highest element in
         // the resultant array
         brr1[l1] = array[i];
         //Used to decrement the frequency of that element
         freq1[brr1[l1]]--;
         l1++;
         for (int j = 0; j < l1; j++) {
            if (i != j) {
               // Calculate GCD
               x1 = __gcd(array[i], brr1[j]);
               // Decrement GCD value by 2
               freq1[x1] -= 2;
            }
         }
      }
   }
   printArr(brr1, size1);
}
// Driver code
int main(){
   /* int array[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 6, 6, 6, 8, 11, 13, 3, 3}; */
   int array[] = { 6, 1, 1, 13};
   int n1 = sizeof(array) / sizeof(array[0]);
   findNumbers(array, n1);
   return 0;
}

輸出

13 6

更新時間:2020-7-25

287 次瀏覽

開始你的 職業

透過完成課程獲得認證

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