Finding GCD of a set of numbers?

后端 未结 2 1819
太阳男子
太阳男子 2020-12-30 18:31

So, I was asked this question in an interview. Given a group of numbers (not necessarily distinct), I have to find the multiplication of GCD\'s of all possible subsets of th

2条回答
  •  隐瞒了意图╮
    2020-12-30 18:36

    Assume that each array element is an integer in the range 1..U for some U.

    Let f(x) be the number of subsets with GCD(x). The solution to the problem is then the sum of d^f(d) for all distinct factors 1 <= d <= U.

    Let g(x) be the number of array elements divisible by x.

    We have

    f(x) = 2^g(x) - SUM(x | y, f(y))
    

    We can compute g(x) in O(n * sqrt(U)) by enumerating all divisors of every array element. f(x) can be computed in O(U log U) from high to low values, by enumerating every multiple of x in the straightforward manner.

提交回复
热议问题