# Number of distinct prime factors of first n natural numbers

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.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 :

## C++

 `// C++ program to find prime factorization upto n natural number ` `// O(n*Log n) time with precomputation ` `#include ` `using` `namespace` `std; ` `#define MAXN 100001 ` ` `  `// Stores smallest prime factor for every number ` `int` `spf[MAXN]; ` ` `  `// Adjacency vector to store distinct prime factors  ` `vector<``int``>adj[MAXN]; ` ` `  `// Calculating SPF (Smallest Prime Factor) for every ` `// number till MAXN. ` `// Time Complexity : O(nloglogn) ` `void` `sieve() ` `{ ` `    ``spf = 1; ` `        ``// marking smallest prime factor for every ` `        ``// number to be itself. ` `    ``for` `(``int` `i=2; i My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.