如何使内循环更有效?

时间:2016-10-09 07:31:12

标签: java

我是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但是如何才能使内循环更有效?

3 个答案:

答案 0 :(得分:3)

这里涉及一点点数论,但是如果你这样做,那么特别是当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();
}

答案 1 :(得分:1)

您可以使用以下事实:对于a的每个除数ib都有a * b = i个。{/ p>

找到所有除数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)次操作。

答案 2 :(得分:0)

此代码时间复杂度为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