簡體   English   中英

如何使 for 內循環更有效率?

[英]How to make the for inner loop more efficient?

我是 Java 新手,有一個問題讓我感到疑惑。 如何使此代碼中的 for 內部循環更有效?

    for (int i = 2; i <= 100; i++) {
        System.out.print("Factors of " + i + " is: ");
        for (int j = 2; j < i; j++) {
            if (i % j == 0)  System.out.print(j + " ");
        }
        System.out.println();
    }

我只是想得到從 2 到 100 的數字的因數,但我怎樣才能使內循環更有效率?

這里涉及到一點數論,但如果你這樣做,當100被更大的東西取代時,它會特別有效:

for (int i = 2; i <= 100; i++) {
    System.out.print("Factors of " + i + " is: ");
    for (int j = 2; j <= (int) Math.sqrt(i); j++) {
        if (i % j == 0)  System.out.print(j + " " + i / j + " ");
    }
    System.out.println();
}

您可以使用這樣一個事實,即對於i每個除數a都有一個數字b使得a * b = i

找到所有除數a <= sqrt(i)並保存b = i/a並稍后打印這些值。

final int num = 100;
int[] divisors = new int[(int) Math.sqrt(num)];
for (int i = 2; i <= num; i++) {
    System.out.print("Factors of " + i + " is: ");
    int j = 2;
    int index = 0;
    for (; j * j < i; j++) {
        if (i % j == 0) {
            System.out.print(j + " ");
            divisors[index++] = i / j;
        }
    }
    if (j * j == i) {
        // print sqrt(i) only once, if it's integral
        System.out.print(j + " ");
    }
    while (--index >= 0) {
        System.out.print(divisors[index] + " ");
    }
    System.out.println();
}

這樣你的內部循環只需要O(sqrt(i))而不是O(i)操作。

此代碼時間復雜度為O(N2)

 public static void main(String[] args) {

        for (int i = 2; i <= 100; i++) {
        System.out.print("Factors of " + i + " is: ");
        for (int j = i/2; j > 1; j--) {
            if (i % j == 0)  System.out.print(j + " ");
        }
        System.out.println();
    }

  }

試試這個,因為你的代碼輸出將顯示如下(升序)

Factors of 24 is: 2 3 4 6 8 12 

請注意,但此給定代碼將顯示輸出如下(降序)

Factors of 24 is: 12 8 6 4 3 2 

暫無
暫無

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

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