问题
Input for this problem is an array A of positive integers and single positive integer k. The output of the program is True if k is in the set S defined below, False otherwise.
Define the set S as follows:
- if x is in A then x is in S
- if x and y are in S, then GCD(x,y) is in S
- if x and y are in S, then LCD(x,y) is in S
Additional constraints: The size of the array A is ≤ 50000, k ≤ 1012, and x ≤ 1012 for each x in A. The program must return an answer in 1 second or less.
I don't have any good idea. The only thing I can think of is to find GCD and LCM of any pair of integers in the array, then I can enlarge the set S. But as the S is expanding, the new integers will be new pairs to make more GCDs and LCMs.
I hope you guys help me. I have been stuck with this for long.
Update:
For instance an array is given is A= { 10, 12, 15 };
As we have mentioned, the S = {..., 10, 12, 15, ...}
We know that 10, 12, 15 is in S. So their GCD and LCM is in S too. Which means:
GCD(10, 12) = 2 in S
GCD(10, 15) = 5 in S
GCD(12, 15) = 3 in S
LCM(10, 12) = 60 in S
...
Finally:
S = { 1, 2, 3, 5, 10, 12, 15, 30, 60 }
回答1:
Factor k into powers of distinct primes. For each such prime power factor, compute the GCD of all array elements of which it is a divisor. If (and only if) some GCD is not a divisor of k, then S does not contain k.
The correctness proof involves the fact that the positive integers are a distributive lattice with operators GCD and LCM.
来源:https://stackoverflow.com/questions/34471157/algorithm-gcd-and-lcm-problems