It is not possible to decompose the number х into factors:

 for (int i = 1; i <= x; i++) { if (x % i == 0) { a = i; System.out.print(a + " ") } } 
  • This code does not decompose x into factors, but searches for all the numbers into which this x is divided completely. - Akina

2 answers 2

  1. We take the checked number ( currentValue is a copy of the number so as not to spoil the original) and the first multiplier equal to 2 .
  2. If the checked number is a multiple of the multiplier, then we print the multiplier on the screen as appropriate, and divide the checked number by the multiplier.
  3. If the multiplier does not fit, then go to the next multiplier ( +1 in case of 2 and +2 in other cases).
  4. Repeat steps 2 and 3 until the value being checked is greater than 1 , and the multiplier is less than the square root of the original number ( sqrt ).
  5. If the tested value is not equal to 1 after the cycle, then output it.

     int x = 660; double sqrt = Math.sqrt(x); int currentValue = x; int multiplier = 2; while (currentValue > 1 && multiplier <= sqrt) { if (currentValue % multiplier == 0) { System.out.print(multiplier + " "); currentValue /= multiplier; } else if (multiplier == 2) { multiplier++; } else { multiplier += 2; } } if (currentValue != 1) { System.out.print(currentValue); } 
  • Well, at least, it makes no sense to try to divide into even ones. And, by the way, if x is a large prime number, will you still check all the multiplier values ​​from 2 to x itself? until you get to the original value? - Harry
  • @Harry pass to x , not to sqrt(x) is yes, an error in the implementation of the algorithm. Passing through only odd and 2 is already an optimization. Corrected the answer, thanks. - Regent

This is a mockery - to sort through everything ...
Look, for example, here is a recent question.

I'm not a whale in Java, so I’ll tell you in words (in C ++, see the link below).
If you do not build a table of prime numbers, then
1. While N is even, divide by 2 and write 2 as one of the dividers (there may be several).
2. Now N is odd. Starting from 3, we check all odd numbers, up to the square root of N (checking i * i <= N for simplicity, and not calculating the root) for divisibility. If it is not divided into one, write the last simple factor - N itself, and complete the work.
3. If it is divided, we write out the next divisor, divide N into it, and repeat the cycle from step 2 for the new value N, starting not from 3, but from the last found divider.

That's all.