You have to increase i
if i
no longer divides the number. You can do this by dividing the number by i
, or increase it otherwise:
long i = 2; // start with 2, not 1
while (i < number) { // and don't end with the number itself
if (number % i == 0) {
factor += i+", "; // add i, not x; and add it to factor, not to number
number /= i;
} else {
i++;
}
}
return factor; // return factor, not number
This also fixes the output to contain commas. You could alternatively use a List<Integer>
to add all divisors to if you don't simply want to print the list, but use it in the code.