Answer the question
In order to leave comments, you need to log in
How to improve the algorithm for finding factors of a number?
Actually, the simplest task from the book is to improve the algorithm for finding all the numbers j, into which any number i is divisible without a remainder, except for itself.
public class Main {
public static void main(String[] args) {
for(int i=2; i <= 100; i++) {
System.out.print("Factors of " + i + ": ");
for (int j = 2; j < i; j++)
if ((i % j) == 0) {
System.out.print(j + " ");
// if (j == i/2) break;
}
System.out.println();
}
}
}
Answer the question
In order to leave comments, you need to log in
improvement 1 so as not to write an extra check in the for loop (int j = 2; j < i/2; j++)
Proving that this is correct is very easy. Let's assume that there is a divisor > j / 2. Divide and get the result < 2. Do not forget that formally the number is divisible by itself.
If you were interested in the simplicity of a number, and not the list of all its divisors, it would be enough to check up to the root of j. Which is also easy to prove by contradiction.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question