在 C++ 中查詢一個整數 X,它是陣列中除一個元素之外所有元素的約數
概念
對於給定的整數陣列,我們的任務是確定一個整數 B,它是除陣列中恰好一個元素之外的所有元素的約數。
需要注意的是,所有元素的最大公約數 (GCD) 不是 1。
輸入
arr[] = {8, 16, 4, 24}
輸出
8 8 is the divisor of all except 4.
輸入
arr[] = {50, 15, 40, 41}
輸出
5 5 is the divisor of all except 41.
方法
我們建立一個字首陣列 A,使得位置或索引 i 包含從 1 到 i 的所有元素的最大公約數。類似地,建立一個字尾陣列 C,使得索引 i 包含從 i 到 n-1(最後一個索引)的所有元素的最大公約數。可以看出,如果 A[i-1] 和 C[i+1] 的最大公約數不是 i 位置元素的約數,那麼它就是所需答案。
示例
// C++ program to find the divisor of all // except for exactly one element in an array. #include <bits/stdc++.h> using namespace std; // Shows function that returns the divisor of all // except for exactly one element in an array. int getDivisor1(int a1[], int n1){ // If there's only one element in the array if (n1 == 1) return (a1[0] + 1); int A[n1], C[n1]; // Now creating prefix array of GCD A[0] = a1[0]; for (int i = 1; i < n1; i++) A[i] = __gcd(a1[i], A[i - 1]); // Now creating suffix array of GCD C[n1-1] = a1[n1-1]; for (int i = n1 - 2; i >= 0; i--) C[i] = __gcd(A[i + 1], a1[i]); // Used to iterate through the array for (int i = 0; i <= n1; i++) { // Shows variable to store the divisor int cur1; // now getting the divisor if (i == 0) cur1 = C[i + 1]; else if (i == n1 - 1) cur1 = A[i - 1]; else cur1 = __gcd(A[i - 1], C[i + 1]); // Used to check if it is not a divisor of a[i] if (a1[i] % cur1 != 0) return cur1; } return 0; } // Driver code int main(){ int a1[] = { 50,15,40,41 }; int n1 = sizeof(a1) / sizeof(a1[0]); cout << getDivisor1(a1, n1); return 0; }
輸出
5
廣告