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