![]() |
VOOZH | about |
Given an array arr[] of integers, find the prime factorization of each number efficiently using Sieve that stores the smallest prime factor (SPF).
Examples:
Input: arr[] = [15, 17, 21]
Output: [[3, 5], [17], [7, 3]]
Explanation: prime factors of:
15 -> 3, 5 as 3* 5 = 15
17, as 17 itself is a prime number so there is no other prime factors of 17
21 ->3, 7 as 3* 7 = 21
Prerequisites :Sieve of Eratosthenes, Least prime factor of numbers till n.
Approach:
To solve this problem, we first need the Smallest Prime Factor (SPF) of each number, as SPF allows us to repeatedly divide a number by its smallest prime factor until it becomes 1, through which we can easily get its prime factors.
To calculate to smallest prime factor for every number we will use the modified approach of sieve of eratosthenes.
The key idea is to precompute the smallest prime that divides each number. Once this SPF array is prepared, theafactorizationfunctionwill calculate the prime factors of the integers of the array.
Step-by-step approach of above idea:
MAXN equal to 100001, representing the upper limit for precomputation.spf of size MAXN + 1, initialized with 1, to store the smallest prime factor (SPF) of every number up to MAXN.sieve() to precompute the smallest prime factor for all numbers up to MAXN using a modified Sieve of Eratosthenes, in which the smallest prime factor for the all the number is initially set to 1.getFactorization() that returns the prime factorization of a number of array using the precomputed spf array.getFactorization(), the sieve() function is called to precompute the smallest prime factor of every number up to MAXN for every number of array the smallest prime factor of that number is repeatedly added to a result vector, and the number is divided by that factor until it becomes 1. The implementation for the above method is given below :
Output:
3 5
17
3 7
Time Complexity: O(log n), for each query.
The precomputation for smallest prime factor is done in O(n log log n) using sieve. Whereas in the calculation step we are dividing the number every time by the smallest prime number till it becomes 1. So, let's consider a worst case in which every time the SPF is 2 . Therefore will have log n division steps. Hence, We can say that our Time Complexity will be O(log n) in worst case.
Auxiliary Space: O(1)
Note : The above code works well for n up to the order of 10^7. Beyond this we will face memory issues.