Saturday, 16 Oct 2021

# Find an element which is coprime with all elements of a given array

Find an element which is coprime with all elements of a given array
Given an array arr[] consisting of N positive integers, the task is to find an integer greater than 1 which is coprime with all the given array elements.
Examples:

Input: arr[ ] = {10,13,17,19}Output: 23Explanation: The GCD of 23 with every array element is 1. Therefore, 23 is coprime with all the given array elements.
Input: arr[] = {13, 17, 23, 24, 50}Output: 53Explanation: The GCD of 53 with every array element is 1. Therefore, 53 is coprime with all the given array elements.

Approach: The idea is to use the fact that a prime number greater than the maximum array element will be coprime with all the given array elements. Therefore, simply find the prime number greater than the largest element present in the array.Below is the implementation of the above approach:

Python3

import math

def find_X(arr):

R = max(arr)

prime = [True for i in range(0, 1000001)]

p = 2
while (p * p R and prime[i] == True:

return i

arr = [10, 13, 17, 19]
print(find_X(arr))

Output:

23

Time Complexity: O(N*log(N))Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.