712230. Prime Factorization using Sieve
Medium
Prime Factorization using Sieve
Summary
Given a number n, find its prime factors. This problem involves understanding how to efficiently identify and extract prime numbers, which is crucial in various algorithms such as RSA encryption. We'll use the sieve of Eratosthenes algorithm to solve this problem.
Detailed Explanation
The sieve of Eratosthenes algorithm works by iteratively marking the multiples of each prime number starting from 2. The left over numbers are prime numbers themselves. Here's a step-by-step breakdown:
- Create an array
isPrimeof sizen+1, initialized with all values set totrue. This represents whether a number is prime or not. - Iterate through the array, starting from the second element (index 1). For each element at index
i, if it's still marked astrue(i.e., it's a prime number), mark its multiples asfalse. - Once the iteration is complete, iterate through the array again and find all elements that are still marked as
true. These are the prime numbers. - For each prime number, find its factors by iterating from 2 to the square root of the prime number. If a factor is found, add it to the list of factors for the prime number.
Time complexity: O(n log log n) Space complexity: O(n)
Optimized Solutions
Java
public class PrimeFactorization {
public static List<Integer> sieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= Math.sqrt(n); i++) {
if (isPrime[i]) {
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
List<Integer> primeFactors = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
int factors = 0;
for (int j = 2; Math.pow(j, 2) <= i; j++) {
if (i % j == 0) {
factors++;
}
}
primeFactors.add(factors);
}
}
return primeFactors;
}
}