GCD of an array

微笑、不失礼 提交于 2019-12-14 03:32:06

问题


You are given an array A of integers of size N. You will be given Q queries where each query is represented by two integers L, R. You have to find the gcd(Greatest Common Divisor) of the array after excluding the part from range L to R inclusive

MY Approach :

public static int gcd(int a ,int b) {
    if(b == 0) return a;
    return gcd(b, a % b);
}

for(int j = 0; j < Q; j++) {
    int l = in.nextInt();
    int r = in.nextInt();
    ans = 0;
    for(int k = 1; k <= n; k++) {
        if(k < l || k > r) ans = gcd(a[k], ans);
    }
    System.out.println(ans);
}

But This approach give me Time Limit Exceeded Error How can i improve my alogrithm


回答1:


You can precompute the gcd for each prefix and suffix(let's call it gcdPrefix and gcdSuffix) in O(n * log MAX_A) time(just iterate over your array from left to right and store the current gcd, then do the same thing from right to left). The answer for a (L, R) query is gcd(gcdPrefix[L - 1], gcdSuffix[R + 1])(so it is O(log MAX_A) operations per query). The total time complexity is O((n + q) * log MAX_A). I think it should be fast enough.



来源:https://stackoverflow.com/questions/27753369/gcd-of-an-array

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