[SOLUTION] Smallest Excluded LCM SOLUTION CODECHEF

Problem SOLUTION CODECHEF

You are given an array  containing  integers.
Find the smallest integer  that doesn’t occur as the LCM of some subsequence of .

The LCM (lowest common multiple) of a set of integers is the smallest positive integer that is a multiple of them all.
For example, LCM(2,3)=6,LCM(4,5,8,1)=40,LCM(13)=13.

Input Format

  • The first line of input will contain a single integer , denoting the number of test cases.
  • Each test case consists of two lines of input.
    • The first line of each test case contains a single integer  — the number of elements of the array.
    • The second line contains  space-separated integers �1,�2,…,��.

Output Format

For each test case, output on a new line the smallest integer that cannot be obtained as the LCM of any subsequence of .

Constraints

  • 1≤�≤1000
  • 1≤�≤105
  • 1≤��≤109
  • The sum of  across all test cases does not exceed 105.

Sample 1:

Input

Output

3
5
1 2 3 4 5
3
2 3 4
4
1 2 3 5
7
1
4

Explanation:

Test case 1: Everything from 1 to 5 already appears in , and we obtain 6=LCM(2,3).
7 cannot be obtained as the LCM of any subsequence, hence it is the answer.

Test case 2: 1 doesn’t appear as the LCM of any subsequence of [2,3,4].

Test case 3: 1,2,3 all appear in the array, while 4 isn’t the LCM of any subsequence.

SOLUTION

import math

def smallest_unobtainable_lcm(N, arr):
arr.sort()
lcm = arr[0]

for i in range(1, N):
gcd = math.gcd(lcm, arr[i])
lcm = (lcm * arr[i]) // gcd

if lcm > 1:
return lcm
else:
return -1

# Input
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int, input().split()))
result = smallest_unobtainable_lcm(N, A)
print(result)

Leave a Comment