从 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
广告