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 + " ") } } currentValue is a copy of the number so as not to spoil the original) and the first multiplier equal to 2 .+1 in case of 2 and +2 in other cases).1 , and the multiplier is less than the square root of the original number ( sqrt ).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); } multiplier values from 2 to x itself? until you get to the original value? - Harryx , 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. - RegentThis 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.
Source: https://ru.stackoverflow.com/questions/611909/
All Articles
xinto factors, but searches for all the numbers into which thisxis divided completely. - Akina