如何显示一个数字的所有因素?(已编辑)

时间:2014-02-21 06:41:02

标签: java methods static-methods factorization

    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; 

我需要我的方法来显示所有因素,现在它只显示一个因素。有人告诉我列表,但我无法上班。

1 个答案:

答案 0 :(得分:0)

如果i不再对数字进行除法,则必须增加i。您可以通过将数字除以i来实现此目的,否则将其增加:

    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

这也会修复输出以包含逗号。如果您不想打印列表,可以使用List<Integer>添加所有除数,但在代码中使用它。