Question

    I need help on fixing my FactorX method. It needs to be like this>>.. The factors of x. (For example, if x is 120 then the factors would be 2, 2, 2, 3, 5). 



            ppublic static String factorX(long x){
            String factor="";
            long number = x;
            long i = 2;  
            while (i < number) {  
                    if (number % i == 0) {
                    factor += i+", "+i+", "; 
                    number /= i;

                } else {
                    i++;
                }
            }

            return factor; 

I need my method to show all factors, now it is showing only one. I was told about List, but I cannot make to work.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top