Find an integer X which is divisor of all except exactly one element in an array in C++

C++Server Side ProgrammingProgramming

Concept

With respect of a given array of integers, our task is to determine an integer B which isthe divisor of all except for exactly one element in the given array.

It should be noted that the GCD of all the elements is not 1.

Input 

arr[] = {8, 16, 4, 24}

Output 

8
8 is the divisor of all except 4.

Input  

arr[] = {50, 15, 40, 41}

Output  

5
5 is the divisor of all except 41.

Method

We create a prefix array A such that position or index i contains the GCD of all the elements from 1 to i. In the similar way, create a suffix array C such that index i contains the GCD of all the elements from i to n-1 (last index). It has been seen that if the GCD of A[i-1] and C[i+1] is not the divisor of the element at i, then it is the required answer.

Example

 Live Demo

// 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;
}

Output

5
raja
Published on 23-Jul-2020 09:12:30
Advertisements