Problem:You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions:
The elements of the first array are all factors of the integer being considered The integer being considered is a factor of all elements of the second array These numbers are referred to as being between the two arrays. You must determine how many such numbers exist.
for example :Sample Input
2 3 2 4 16 32 96
Sample Output
3
My code:
public static int getTotalX(int n, int m, List<Integer> a, List<Integer> b) { int total=0,x=0,y=0; for(int i=a.get(n-1);i<=b.get(0);i++) { for(int j=0;j<n;j++) { //to check if the elements in list 'a' can divide the integer. if(i%a.get(j)==0) { y++; } } //if every element in list a can divide the integer go forward if(y==n) { for(int k=0;k<m;k++) { //to check if the elements of list 'b' is divisible by integer if(b.get(k)%i==0) { x++; } } y=0; //if every element of 'b' is divisible by integer, count how many such integers are there if(x==m) { total++; x=0; } } } return total; }
My code is not giving proper solution and I cant understand why.
Advertisement
Answer
private static int getTotalX(int n, int m, List<Integer> a, List<Integer> b) { int total = 0, x = 0, y = 0; for (int i = a.get(n - 1); i <= b.get(0); i++) { for (int j = 0; j < n; j++) { if (i % a.get(j) == 0) { y++; } } if (y == n) { for (int k = 0; k < m; k++) { if (b.get(k) % i == 0) { x++; } } if (x == m) { total++; } } // changes here y = 0; x = 0; } return total; }
Great progress. You were very close. Algorithm is on point and efficient.
Only one mistake: you were resetting the variables x
and y
inside the if
conditions.
What if the condition is not true? Then the variables are never reset and all the future computations are done on those wrong values in x
and y
.
Like Java8? Here is a one-liner:
return (int) IntStream.rangeClosed(a.get(n - 1), b.get(0)) .filter(i -> a.stream().filter(value -> i % value == 0).count() == a.size()) .filter(i -> b.stream().filter(value -> value % i == 0).count() == b.size()) .count();