Prime Factorization
Problem
Read an integer n (n is at least 2) and print its prime factors in ascending order, separated by a space. A prime factor is repeated as many times as it divides the number. Example: 12 = 2 x 2 x 3.
Constraints
- 2 <= n <= 10^15
Examples
Input
12
Output
2 2 3
Input
17
Output
17
Solutions
We divide by 2 as many times as possible, then by 3, and so on. A divisor that is not prime never divides, because its prime parts are already removed. If a number larger than 1 remains, it is prime.
/*
* Problem : Write a number as a product of prime numbers.
* Input : One integer n, n >= 2.
* Output : The prime factors in ascending order, separated by a space.
* Approach: Divide by the smallest possible divisor again and again.
* Time : O(sqrt(n))
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
StringBuilder result = new StringBuilder();
// Step 1: Start with the smallest prime number, which is 2.
long divisor = 2;
// Step 2: Stop when divisor * divisor is larger than the rest of the number.
while (divisor * divisor <= number) {
// Step 3: While the divisor divides the number, it is a prime factor. Write it and divide the number.
while (number % divisor == 0) {
if (result.length() > 0) {
result.append(" ");
}
result.append(divisor);
number = number / divisor;
}
// Step 4: Try the next number. Composite divisors never divide, because their prime parts were removed before.
divisor++;
}
// Step 5: If something larger than 1 is left, it is a prime number and it is the last factor.
if (number > 1) {
if (result.length() > 0) {
result.append(" ");
}
result.append(number);
}
// Step 6: Print the prime factors.
System.out.println(result);
}
}
Hints (2)
- Always divide by the smallest divisor first.
- What does the remaining number mean when the loop ends?