Algorithm - GCD and LCM problems

孤者浪人 提交于 2019-12-10 11:44:31

问题


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:

  1. if x is in A then x is in S
  2. if x and y are in S, then GCD(x,y) is in S
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!