1

I'm new to Java and am trying to solve the problem of finding all prime factors of a given number. I have been told if I set the second statement of the for loop to i * i <= userInput instead of i <= userInput, the program will be much more efficient.

I can't get my head around as to why this is the case. What is the reason behind it?

Scanner sc = new Scanner(System.in);
int userInput = sc.nextInt();
        sc.close();
        System.out.println("Prime factors of " + userInput + " include: ");

        for (int i = 2; i * i <= userInput; i++){
            while(userInput % i == 0){
                System.out.print(i + " ");
                userInput /= i;
            }
        }
        if (userInput > 1){
            System.out.print(userInput);
        } else {
            System.out.print("");
        }
halfer
  • 18,701
  • 13
  • 79
  • 158
Thor
  • 8,608
  • 10
  • 43
  • 113

3 Answers3

2

In fact this code will find not only prime factors - it will search for all factors. If your number is Y can be represented as X * X, any factor below X will have matching factor greater than X. So you need only to check half of all cases. For 14 when you found that 2 is factor, matching factor is 7, so you don't need to check matching factor of 7. Thats why your condition is contain i*i.

2

Because it cuts the search space from N to the square root of N.

user207421
  • 289,834
  • 37
  • 266
  • 440
0

You could write as:

for (int i = 2; i <= Math.sqrt(userInput); i++)

This reduces the number of iterations of the loop from N to square root of N. Eg: if N = 16, then the iterations would be reduced to 4. For a smaller N, this does not seem much but you will see the difference as N increases in value.

Imagine N=16, the factors are: 


1,16 --   you are disallowing this anyway but I present if for completeness
2,8
4,4
------ The ones below are already covered and do not need to be looped through --------
8,2
16,1

A faster way to do that would be to find an incrementer and that is linked here.

Khanna111
  • 2,792
  • 17
  • 19