简体   繁体   English

如何使 for 内循环更有效率?

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

I am new to Java and there's this one question that makes me wonder.我是 Java 新手,有一个问题让我感到疑惑。 How to make the for inner loop more efficient in this code?如何使此代码中的 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();
    }

I was just trying to get the factors of numbers from 2 to 100 but how can i make the inner loop more efficient?我只是想得到从 2 到 100 的数字的因数,但我怎样才能使内循环更有效率?

It's a little bit number theory involved here but if you do this it would be efficient specially when the 100 is replaced with something much bigger:这里涉及到一点数论,但如果你这样做,当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();
}

You could use the fact that for every divisor a of i there is a number b such that a * b = i .您可以使用这样一个事实,即对于i每个除数a都有一个数字b使得a * b = i

Find all divisors a <= sqrt(i) and save b = i/a and print these values later.找到所有除数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();
}

This way your inner loop needs only O(sqrt(i)) instead of O(i) operations.这样你的内部循环只需要O(sqrt(i))而不是O(i)操作。

This code time complexity is O(N2) .此代码时间复杂度为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();
    }

  }

Try this,as your code output will be displayed as follows (ascending order)试试这个,因为你的代码输出将显示如下(升序)

Factors of 24 is: 2 3 4 6 8 12 

please be noticed, but this given code will be displayed output as follows (descending order )请注意,但此给定代码将显示输出如下(降序)

Factors of 24 is: 12 8 6 4 3 2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM