G
G
gleendo2016-11-23 17:32:47
Java
gleendo, 2016-11-23 17:32:47

How to reduce the number of iterations of the inner loop?

There is a code example, the result of which is output to the console numbers from 2 to 100 with their divisors without a remainder.
Question: How can the number of iterations of the inner loop be reduced?

public class App {
    public static void main(String[] args) {
        for (int i = 2; i <= 100; i++) {
            System.out.print("Делители " + i + ": ");

            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    System.out.print(j + " ");
                }
            }

            System.out.println("");
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2016-11-23
@saboteur_kiev

It'll do? Twice less.

public class App {
    public static void main(String[] args) {
        for (int i = 2; i <= 100; i++) {
            System.out.print("Делители " + i + ": ");

            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    System.out.print(j + " ");
                }
                j++;
                if (i % j == 0) {
                    System.out.print(j + " ");
                }

            }

            System.out.println("");
        }
    }
}

In general, you do not have a goal, why reduce the iteration.

K
kolaygreha, 2019-02-08
@kolaygreha

I generally combined these two methods and reduced the number of iterations by 4 times! Only j <= i already needs to be written, otherwise sometimes the last divisor is not captured, since the step is essentially equal to two.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question