You are given two arrays AA and BB containing elements each. Choose a pair of elements x,y such that:
x belongs to array AA. y belongs to array BB. gcd(x,y)
is the maximum for all pairs x,y.
If there is more than one such pair x,y having maximum gcd, then choose the one with maximum sum. Print the sum of elements of this maximum-sum pair.
NOTE: returns gcd(x,y)
the largest integer that divides both x and y.
Constraints:
$$1≤N≤5\cdot 10^5$$ $$1≤A_i≤10^6$$ $$1≤B_i≤10^6$$
Input format:
The first line of the input contains n denoting the total number of elements of arrays AA and BB. Next line contains n space separated positive integers denoting the elements of array AA. Next line contains n space separated positive integers denoting the elements of array BB.
Output format:
From all the pairs having maximum gcd , print the sum of one that has the maximum sum.
public class Solution2 {
static int gcdcalc(int x, int y){
if(y == 0)
{
return x;
}
return gcdcalc(y, x%y);
}
static int maximumGcdAndSum(int[] A, int[] B) {
int gcd,sum,maxgcd=0,maxsum=0;
for(int A_i = 0; A_i < A.length; A_i++)
{
for(int B_i = 0; B_i < B.length; B_i++)
{
sum = A[A_i] + B[B_i];
gcd = gcdcalc(A[A_i], B[B_i]);
if(maxgcd < gcd)
{
maxgcd = gcd;
maxsum = sum;
}
if(maxgcd == gcd)
{
if(maxsum < sum)
maxsum = sum;
}
}
}
return maxsum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] A = new int[n];
for(int A_i = 0; A_i < n; A_i++){
A[A_i] = in.nextInt();
}
int[] B = new int[n];
for(int B_i = 0; B_i < n; B_i++){
B[B_i] = in.nextInt();
}
int res = maximumGcdAndSum(A, B);
System.out.println(res);
}
}
y > x
? \$\endgroup\$y > x
, the method will just invokegcdcalc(y, x)
, so it's just one extra recursion. \$\endgroup\$