Prime Factorization using Sieve O ( log n ) for multiple queries | C ++ program to find prime factorization of a number n in O ( Log n ) time with precomputation allowed . ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; driver program for above function ; precalculating Smallest Prime Factor ; calling getFactorization function
#include " bits / stdc + + . h " NEW_LINE using namespace std ; #define MAXN  100001 NEW_LINE int spf [ MAXN ] ; void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } vector < int > getFactorization ( int x ) { vector < int > ret ; while ( x != 1 ) { ret . push_back ( spf [ x ] ) ; x = x / spf [ x ] ; } return ret ; } int main ( int argc , char const * argv [ ] ) { sieve ( ) ; int x = 12246 ; cout << " prime ▁ factorization ▁ for ▁ " << x << " ▁ : ▁ " ; vector < int > p = getFactorization ( x ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) cout << p [ i ] << " ▁ " ; cout << endl ; return 0 ; }