Print factors of number using fencepost loop I was wondering if this code could be optimized in any way? For instance, could I use a for each loop here? Are there other ways I could write this which would make it easier for me, or the person reading it to understand?

public static void printFactors(int factorsOf) {
    for (int i = 1; i &lt; factorsOf; i++) {
        if(factorsOf % i == 0) {
            System.out.print(i + " and ");
        }
    }
    System.out.print(factorsOf);
}
Just a tiny note:


  In number theory, integer factorization is the decomposition of a composite number into a product of smaller integers.


So a factorization of 12 may be

6 * 2


or

3 * 2 * 2


but not

1 and 2 and 3 and 4 and 6 and 12


What you did is finding all divisors and you should name your method appropriately.



As always, a method both computing and printing something is rather unusable. You should always compute the result in one method, so that you can later either print it or process it further.

For simple methods like yours it doesn't matter much, but it's good habit.