I'm trying to answer the following assignment:
We are given two arrays
a
andb
containing elements each.Choose a pair of elements
(x,y)
such that:x
belongs to arraya
;y
belongs to arrayb
;gcd(x,y)
is the maximum of all pairs(x,y)
.If there is more than one such pair having maximum gcd, then choose the one with maximum sum.
Print the sum of elements of this maximum-sum pair.
n
-> size of the input arrays
a
andb
are two arrays consisting ofn
numbers each.
This code is showing segmentation fault. I can't figure out the problem. it is showing segmentation fault for some test cases while for other it runs perfectly.Can you figure out the problem with the code?
#include <stdio.h>
long int max_gcd=0,max_sum=0;
long int n;
long int a[1000000],b[1000000];
long int hcf(long int n1, long int n2)
{
if (n2 != 0)
return hcf(n2, n1%n2);
else
return n1;
}
long int gcd(long int i,long int j,long int n)
{
long int ans=hcf(a[i],b[j]);
if(ans>max_gcd)
{
max_gcd=ans;
max_sum=a[i]+b[j];
}
if(ans==max_gcd && max_sum<a[i]+b[j])
{
max_sum=a[i]+b[j];
}
if(j+1<n)
return gcd(i,j+1,n);
else if(i+1<n)
return gcd(i+1,0,n);
return max_sum;
}
int main()
{
long int i;
scanf("%ld",&n);
for(i=0;i<n;i++)
{
scanf("%ld",&a[i]);
}
for(i=0;i<n;i++)
{
scanf("%ld",&b[i]);
}
long int ans=gcd(0,0,n);
printf("%ld",ans);
return 0;
}