![]() |
VOOZH | about |
Given an integer n, find all unique prime factors of n. A prime factor is a prime number that divides n exactly (without leaving a remainder).
Examples:
Input: n = 100
Output: [2, 5]
Explanation: Unique prime factors of 100 are 2 and 5.
Input: n = 60
Output: [2, 3, 5]
Explanation: Prime factors of 60 are 2, 2, 3, 5. Unique prime factors are 2, 3 and 5.
Table of Content
First, divide
nby 2 repeatedly and store 2 as a unique prime factor if it dividesn. Then, check odd numbers from 3 to √n, for each that dividesn, store it and dividencompletely by it. Finally, ifnis still greater than 2, store it as it is a prime factor.
Step by step approach:
n is divisible by 2.n repeatedly by 2.i from 3 to √n:i divides n, store i as a unique prime factor.n by i until it's no longer divisible.n > 2, it is a prime and should be stored.2 5
The idea in the SPF approach is to precompute the smallest prime factor (SPF) for every number up to
nusing a modified sieve. Once SPF is ready, we can efficiently find the unique prime factors of any number by repeatedly dividing it by its SPF. This makes each factorization run in O(log n) time.
Note: This approach is best for cases where we need to find unique prime factors for multiple input values.
Step by step approach:
spf[] of size n+1, where spf[i] stores the smallest prime factor of i.spf[i] = i for all i.i, mark spf[j] = i for all multiples j of i (if not already marked).n:n by spf[n] (i.e n = n/spf[n]).spf[n] encountered in a set (to keep it unique and in ascending order).n becomes 1.2 5
Time Complexity: O(n*log(log(n))) - The SPF array is built in O(n(log(log(n))) time using the sieve. Then, finding the unique prime factors of a single number n takes O(log(n)) time.
Auxiliary Space: O(n) - The algorithm uses O(n) space for the SPF array, which stores the smallest prime factor for each number up to n.