अवधारणा
पूर्णांकों के दिए गए सरणी के संबंध में, हमारा कार्य एक पूर्णांक 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 तक के सभी तत्वों का GCD होता है। इसी तरह, एक प्रत्यय सरणी सी बनाएं जैसे कि इंडेक्स i में i से n-1 (अंतिम अनुक्रमणिका) के सभी तत्वों का जीसीडी शामिल है। यह देखा गया है कि यदि A[i-1] और C[i+1] का GCD, 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