Answer the question
In order to leave comments, you need to log in
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
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("");
}
}
}
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 questionAsk a Question
731 491 924 answers to any question