Search code examples
javaloopsfor-looparraylistfactors

How would I go about using multiple arraylists to filter factors of a number?


Okay, so say i want to find factors of a number a. I know how to do that, using a for loop and an arraylist. My problem is that (and i have no idea how to go about this) I want the factors in pairs.(that multiply together to get the original number) I would assume I could get the factors in multiple arraylists that each have 2 variables.. but that is extremely unwieldy as different numbers will have different numbers of factors. (Not to mention, I dont know how to do this..)

After this, I want to test those variables in an equation to narrow them down. Say, whichever of those pairs add up to a given number is the one I want to use. I have been trying to figure out how to go about all of this using tutorials but I am completely lost, as I am somewhat new to Java.

Thank you for any and all help :-)


Solution

  • You could create your own class that had fields for each side of the pair, but it would be acceptable and convenient to use a Map<Integer, Integer>. A basic implementation would be:

    private static Map<Integer, Integer> factorize(int number) {
        Map<Integer, Integer> factors = new HashMap<Integer, Integer>();
        for (int i = 1; i < Math.sqrt(number); i++) {
            if (number % i == 0)
                factors.put(i, number / i);
        }
        return factors;
    }
    

    Here's some test code to show how it would be called and what the result is:

    public static void main(String[] args) {
        Map<Integer, Integer> factorPairs = factorize(12345);
        for (Map.Entry<Integer, Integer> factor : factorPairs.entrySet())
            System.out.println(factor.getKey() + " x " + factor.getValue());
    }
    

    Output:

    1 x 12345
    3 x 4115
    5 x 2469
    15 x 823
    

    That should be enough to get you started