Alyamin Smail
Alyamin Smail

Reputation: 63

counting the element of two arrays that are factors of an number

why my code doesnt work I want to count the number of integers that satisfy the 2 condition:

1-The elements of the first array are all factors of the integer being considered

2-The integer being considered is a factor of all elements of the second array

public class Betweentest {

   public static int getTotalX(List<Integer> a, List<Integer> b) {

     Boolean test = true;
     int n=0;

     for(int j=2; j<=b.get(b.size()-1); j++){
        for(int i=0; i<a.size(); i++){
            if(j%a.get(i) != 0){
             test = false;

            }

         }
        if(test == true){
            for(int i=0; i<b.size(); i++){
                if(b.get(i)%j != 0){
                 test = false;

                }
            }
       if(test == true){
         n++;
       }
     }
     return n;
     }

   public static void main(String[] args) {
        List<Integer> a=Arrays.asList( 2, 4);
       List<Integer> b=Arrays.asList( 16, 32, 64);
         System.out.print(getTotalX( a,  b));
      }

 }

Upvotes: 0

Views: 189

Answers (2)

BENMOHAMED Charfeddine
BENMOHAMED Charfeddine

Reputation: 161

That's solution maybe can help you

boolean result =list1.stream().allMatch(n -> n % divisor ==0);
if(result)
    result =list2.stream().allMatch( n-> n % divisor == 0);

System.out.println("result -->" + result);

Upvotes: 0

Eran
Eran

Reputation: 393841

Your code doesn't work because you set your indicator variable test to true only once, before the outer loop begins, so once it changes to false (which happens for the first value of j), it remains false for all the following values of j.

It should be reset inside the loop:

for (int j=2; j<=b.get(b.size()-1); j++) {
    test = true;
    ...
}

Or even better - just declare it inside the loop, since it is not required outside the loop:

for (int j=2; j<=b.get(b.size()-1); j++) {
    boolean test = true;
    ...
}

After making this change, your code produces the expected result 3 for the given input Lists.

Upvotes: 1

Related Questions