The code below is for Hackerrank competition. Seems that it works correctly but performs very slowly and because of it can't pass some tests.
The task is to find the maximum GCD of all possible pairs of two positive integers \$x, (1 \leq x \leq 10^6)\$ and \$y, (1 \leq y \leq 10^6)\$, where \$x\$ belongs to array \$A\$ and \$y\$ belongs to array \$B\$. Both arrays have the same size, \$(1 \leq \text{size} \leq 10^5)\$. If there is more than one pair with the same GCD, then use the GCD with the maximum sum of its numbers i.e. \$(x + y)\$. Print the sum of elements of this maximum-sum pair.
Input is given in the following way
first line - size of the arrays
second line - elements for the first array
third line - elements for the second array
e.g
5
3 1 4 2 8
5 2 12 8 3
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
inline size_t countGcd( size_t n1, size_t n2 ) {
return ( n2 != 0 ) ? countGcd( n2, n1 % n2 ) : n1;
}
int main() {
size_t num = 0;
std::cin >> num;
size_t elem = 0;
std::vector< size_t > arr;
for ( size_t i = 0; i < num; ++i ) {
std::cin >> elem;
arr.push_back( elem );
}
size_t max_sum = 0;
size_t max_gcd = 0;
for ( size_t i = 0; i < num; ++i ) {
std::cin >> elem;
for ( size_t j = 0; j < arr.size(); ++j ) {
size_t gcd = ( ( elem >= arr.at( j ) ) ? ( elem % arr.at( j ) == 0 ? arr.at( j ) : countGcd( elem, arr.at( j ) ) ) : ( arr.at( j ) % elem == 0 ? elem : countGcd( elem, arr.at( j ) ) ) );
if ( gcd > max_gcd ) {
max_sum = elem + arr.at( j );
max_gcd = gcd;
} else if ( gcd == max_gcd ) {
size_t sum = elem + arr.at( j );
if ( sum > max_sum )
max_sum = sum;
}
}
}
std::cout << max_sum << std::endl;
return 0;
}
I tried different GCD implementations ( Euclidean algorithm ( both recursive and iterative ), Binary GCD algorithm ( both recursive and iterative ) ) but without success. Seems that I have to change something inside main function, maybe rid off the if-else
inside the for
-loops but actually have no idea how to do this.
*.stackexchange.com
,ajax.googleapis.com
,cdn.sstatic.net
andcdnjs.cloudflare.com
). \$\endgroup\$