Q: Given an array of n integers, find the maximum value of GCD for all possible pairs.

Sample Test Case- 1 2 3 4 5 Output: 2

2<=n<=10^5

# | User | Rating |
---|---|---|

1 | tourist | 3619 |

2 | Um_nik | 3493 |

3 | ecnerwala | 3446 |

4 | Radewoosh | 3383 |

5 | ksun48 | 3357 |

6 | yosupo | 3324 |

7 | Benq | 3299 |

8 | maroonrk | 3243 |

9 | apiadu | 3238 |

10 | Petr | 3217 |

# | User | Contrib. |
---|---|---|

1 | Errichto | 207 |

2 | Monogon | 196 |

3 | SecondThread | 195 |

4 | vovuh | 188 |

5 | pikmike | 186 |

5 | Um_nik | 186 |

7 | antontrygubO_o | 185 |

8 | Ashishgup | 182 |

9 | pashka | 169 |

10 | Radewoosh | 167 |

Q: Given an array of n integers, find the maximum value of GCD for all possible pairs.

Sample Test Case- 1 2 3 4 5 Output: 2

2<=n<=10^5

↑

↓

Codeforces (c) Copyright 2010-2020 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Oct/30/2020 19:43:55 (f3).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

Take a look at this post.

Mark all divisors of each element, in O(sqrt(n)). Then find maximum element of mark array that is marked more than twice, in O(n).

Please explain more. I don't understand anything.

for(int i=0;i<n;i++) { for(int j=1;j*j<=a[i];j++) { if(a[i]%j==0) { mark[j]++; mark[a[i]/j]++; } } } complexity is O(N*SQRT(MAX(A)))

I understood. Thank you.

Hey its really urgent thanks to your post that i could get max gcd of all pairs so fast but i really also need to know for which such pair is it the max wrt your solution how do i calculate which pair it is ?? Please help and reply asap

I solved a cses problem using this method but got TLE for some cases. I need more efficient or some modification over this.

Hey its really urgent thanks to your post that i could get max gcd of all pairs so fast but i really also need to know for which such pair is it the max wrt your solution how do i calculate which pair it is ?? Please help and reply asap

If you are referring to the problem from the yesterday contest on CodeChef, I got AC in

O(MaxA*log(MaxA)) by trying all possible GCDs and seeing if there are at least two numbers that divide it, same as mentioned in the post (link given in the first comment). However, it required some optimization to actually fit it into the TL (Like clearing the array of used digits inO(N) rather than inO(MaxA).). I wonder if there is a solution that doesn't depend on the values of numbers and is fast enough.This question is close with HackerRank WoC 34 #2 (https://www.hackerrank.com/contests/w34/challenges/maximum-gcd-and-sum), please don't answer comments like written today and from "fake" accounts till end of competition. However, there is answer in comments...

Good luck

For the next week, not just for today :)

Oh really?! Obviously you got that. I'm no way trying to get the code. I had doubt that's it. Thanks a lot.Whatever, I'll figure it out.

Good luck then!