【问题标题】:Find minimum GCD of a pair of elements in an array查找数组中一对元素的最小 GCD
【发布时间】:2019-09-04 11:37:19
【问题描述】:

给定一个元素数组,我必须找到 MINIMUM GCD 可能 时间复杂度最小的任意两对数组之间。

例子

输入

arr=[7,3,14,9,6]

约束

N= 10^ 5

输出

1

解释

min gcd can be of pair(7,3)

我的幼稚解决方案 - O(n^2) 糟糕的幼稚蛮力

int ans=INT_MAX;

for (int i = 0; i < n; ++i)
{
    for(int j=i+1; j<n; j++){
        int g= __gcd(arr[i],arr[j]);
        ans=min(ans,g);
    }
}

return ans;

您能推荐一种时间复杂度最低的更好方法吗?

【问题讨论】:

  • 要回答这个问题,必须了解有关列表中整数的大小及其分布的更多信息。例如,如果列表确实总是 100,000 长并且整数是随机生成的,那么算法中的 gcd 应该很快达到 1,此时您可以简单地退出程序。

标签: primes prime-factoring number-theory greatest-common-divisor modular-arithmetic


【解决方案1】:

这个解决方案的工作时间为 O(n + h log h),其中 h 是数组中的最大数。让我们解决一个更难的问题:对于每个 x

莫比乌斯反演可用于解决以下问题:您需要找到一个数组 y,但给定一个数组 z,使得 z[k] = y[k] + y[2*k] + y [3*k] + .... 令人惊讶的是,它就地工作,而且只需要三行代码!

这正是我们所需要的,首先我们会找到有序对的数量 (i, j) 使得 d[x] GCD(a[i], a[j] ),但我们需要有序对 (i, j) 的数量,使得 d[x] GCD(a[i], a[j])。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

typedef long long ll;

int main() {
    int n, h = 0;
    cin >> n;
    vector<int> a(n);
    for (int& x : a) {
        cin >> x;
        h = max(h, x);
    }
    h++;
    vector<ll> c(h), d(h);
    for (int x : a)
        c[x]++;

    for (int i=1; i<h; i++)
        for (int j=i; j<h; j+=i)
            d[i] += c[j];

    // now, d[x] = no. of indices i such that x divides a[i] 

    for (int i=1; i<h; i++)
        d[i] *= d[i];

    // now, d[x] = number of pairs of indices (i, j) such that
    // x divides a[i] and a[j] (just square the previous d)
    // equiv. x divides GCD(a[i], a[j])

    // apply Mobius inversion to get proper values of d
    for (int i=h-1; i>0; i--)
        for (int j=2*i; j<h; j+=i)
            d[i] -= d[j];

    for (int i=1; i<h; i++) {
        if (d[i]) {
            cout << i << '\n';
            return 0;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2010-12-12
    相关资源
    最近更新 更多