What is the efficient algorithm to find the maximum Greatest Common Divisor of N numbers? Input: First line contains N (2<=N<=10^5). Next line contains N numbers, each of them more than 1 and less than 10^5, output: Output the largest GCD of any pair of numbers.
https://www.hackerrank.com/contests/w34/challenges/maximum-gcd-and-sum
Come on dude. Cant wait 10 hours more?
I wasn't aware of that contest, I was solving the C problem on the following link: http://codeforces.me/gym/101370/attachments/download/5499/20092010-summer-petrozavodsk-camp-petr-mitrichev-contest-5-en.pdf
Assign v, v[x] = 1 if there was a number divisible by x. Go with i through the array. Find all divisors of a[i], for each divisor x, if v[x] = 1 update maximum with x. Solution O(N^1.5).
You can iterate over all possible gcds and for each check if there exist two or more numbers divisable by it (and if there are, choose two largest).
If you do it in way like this:
for (int gcd = 1; gcd < m; gcd++) {
for (int i = gcd; i < m; i += gcd) {
...
it will work in O(m log m) because m/1 + m/2 + m/3 + ... + 1/m = m * (1/1 + 1/2 + 1/3 + ... + 1/m) = m * O(log m) = O(m log m)