Search code examples
javaloopsarraylistmultiplicationmodulo

How would I find the first 5 multiples of 4, 5, and 6 and add them to an ArrayList?


I have a homework assignment that needs me to write a method that, given a list, will remove all multiples of 3 and add the first 5 multiples of 4, 5, and 6. It will then add that list to a HashSet, removing the duplicate integers, and return the size of the HashSet.

I've figured out everything else in this problem save for the "add first 5 multiples of 4, 5, and 6". My current code is the one I'm stuck with, using a for loop to iterate from 1 to 30. However, given an empty list, this adds 28, which is the 7th multiple of 4. I've tried nesting loops so I can iterate to 30 while at the same time iterating to 5, but none of my attempts have worked. Can anyone help me out?

Below is my current code.

public static int modify(List<Integer> list) {
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) == null) {
            throw new IllegalArgumentException("Cannot be null.");
        }
        if (list.get(i) % 3 == 0) {
            list.remove(i);
        }
    }

    for (int i = 1; i <= 30; i++) {
        if (i % 4 == 0) {
            list.add(i);
        }
        if (i % 5 == 0) {
            list.add(i);
        }
        if (i % 6 == 0) {
            list.add(i);
        }
    }

    Collections.sort(list);
    HashSet<Integer> unique = new HashSet<Integer>();
    unique.addAll(list);
    return unique.size();
}

Solution

  • Instead of counting to 30 and checking for incidences of multiples of 4, 5, and 6, why don't you find the multiples directly?

    for (int i = 1; i <= 5; i++) {
        list.add(4 * i);
        list.add(5 * i);
        list.add(6 * i);
    }
    

    If there are any duplicates, they'll be removed when you add them to the HashSet.

    Side note: I'm not sure why you're bothering to sort the list before you add them to the HashSet. Sets inherently have no order so it doesn't matter if the list is sorted or not.