VOOZH about

URL: https://www.geeksforgeeks.org/dsa/prime-factor/

⇱ Distinct Prime Factors - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Distinct Prime Factors

Last Updated : 9 May, 2026

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.

Factorization using Trial Division - O(sqrt(n)) Time and O(log(n)) Space

First, divide n by 2 repeatedly and store 2 as a unique prime factor if it divides n. Then, check odd numbers from 3 to √n, for each that divides n, store it and divide n completely by it. Finally, if n is still greater than 2, store it as it is a prime factor.

Step by step approach:

  • Start by checking if n is divisible by 2.
    • If yes, store 2 as a unique prime factor and divide n repeatedly by 2.
  • Loop through odd numbers i from 3 to √n:
    • If i divides n, store i as a unique prime factor.
    • Keep dividing n by i until it's no longer divisible.
  • After the loop, if n > 2, it is a prime and should be stored.
  • This ensures all unique prime factors are captured efficiently.
  • The algorithm avoids duplicates by fully removing each prime factor once found.

Output
2 5 

Sieve of Eratosthenes (Smallest Prime Factor)

The idea in the SPF approach is to precompute the smallest prime factor (SPF) for every number up to n using 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:

  • Precompute spf for every number up to n:
    • Create an array spf[] of size n+1, where spf[i] stores the smallest prime factor of i.
    • Initialize spf[i] = i for all i.
    • Use the Sieve of Eratosthenes, for each prime i, mark spf[j] = i for all multiples j of i (if not already marked).
  • To find unique prime factors of a number n:
    • Repeatedly divide n by spf[n] (i.e n = n/spf[n]).
    • Store each new spf[n] encountered in a set (to keep it unique and in ascending order).
    • Continue until n becomes 1.

Output
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.

Practice problems for finding prime factors


Comment
Article Tags:
Article Tags: