VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-distinct-prime-factors-of-first-n-natural-numbers/

⇱ Number of distinct prime factors of first n natural numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of distinct prime factors of first n natural numbers

Last Updated : 11 Jul, 2025

In this article, we study an optimized way to calculate the distinct prime factorization up to n natural number using O O(n*log n) time complexity with pre-computation allowed.
Prerequisites: Sieve of Eratosthenes, Least prime factor of numbers till n.
 


 

Key Concept: Our idea is to store the Smallest Prime Factor(SPF) for every number. Then to calculate the distinct prime factorization of the given number by dividing the given number recursively with its smallest prime factor till it becomes 1. 
 


To calculate to smallest prime factor for every number we will use the sieve of eratosthenes. In original Sieve, every time we mark a number as not-prime, we store the corresponding smallest prime factor for that number (Refer this article for better understanding).
The implementation for the above method is given below :
 


Output
Distinct prime factor for first 10 natural number : 0 1 1 1 1 2 1 1 1 2 
Comment
Article Tags:
Article Tags: