D
D
Denis Karakchiev2015-08-19 21:06:26
Java
Denis Karakchiev, 2015-08-19 21:06:26

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();
              }
  }
}

Actually, you need to reduce the number of iterations in the nested loop. My solution in the form of a documented line of code seems to work. The question is this: the solution seems too naive, because it was brought about by 'straight swotting'. Those. I looked at the result of the code, saw that the value of the number by which i is divided without a remainder never turns out to be more than 1 \ 2 from i and added such a line.
So, is there a less naive way, or a completely different one, which should be noted?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2015-08-19
@Satori_Kanzo

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 question

Ask a Question

731 491 924 answers to any question