簡體   English   中英

如何顯示數字的所有因子?(已編輯)

[英]How to show all factors of a number?(Edited)

    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; 

我需要我的方法來顯示所有因素,現在只顯示一個。 有人告訴我有關List的信息,但我無法工作。

如果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>將所有除數添加到其中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM