CSES - Common Divisor
Authors: Andrew Wang, Andi Qu
Appears In
Solution 1
Time Complexity:
The naive approach would be to brute-force each pair of numbers in the array and calculate the maximum GCD. Sadly, this solution gets TLE on half of the test cases.
#include <iostream>using namespace std;int arr[200000];int gcd(int a, int b){if(b == 0) return a;return gcd(b, a%b);}int main() {ios_base::sync_with_stdio(0);
Solution 2
Time Complexity:
Maintain an array, , to store the count of divisors. For each value in the array, find its divisors and for each in those divisors, increment by one. The greatest GCD shared by two elements in the array will be the greatest index in our stored count for divisors with a count greater than or equal to .
#include <iostream>using namespace std;int cnt[1000001]; //stores count of divisorsint main() {ios_base::sync_with_stdio(0);cin.tie(0);int n; cin >> n;for (int i = 0; i < n; i++){int a; cin >> a;
Solution 3
Time Complexity:
Given a value, , we can check whether a pair has a GCD equal to by checking all the multiples of . With that information, loop through all possible values of and check if it is a divisor to two or more values. This works in since
#include <bits/stdc++.h>using namespace std;int cnt[1000001];int main() {ios_base::sync_with_stdio(0);cin.tie(0);int n;cin >> n;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!