Prime Factorization using Sieve O ( log n ) for multiple queries | Python3 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 prime factorization by dividing by smallest prime factor at every step ; precalculating Smallest Prime Factor ; calling getFactorization function
import math as mt NEW_LINE MAXN = 100001 NEW_LINE spf = [ 0 for i in range ( MAXN ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , mt . ceil ( mt . sqrt ( MAXN ) ) ) : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def getFactorization ( x ) : NEW_LINE INDENT ret = list ( ) NEW_LINE while ( x != 1 ) : NEW_LINE INDENT ret . append ( spf [ x ] ) NEW_LINE x = x // spf [ x ] NEW_LINE DEDENT return ret NEW_LINE DEDENT sieve ( ) NEW_LINE x = 12246 NEW_LINE print ( " prime ▁ factorization ▁ for " , x , " : ▁ " , end = " " ) NEW_LINE p = getFactorization ( x ) NEW_LINE for i in range ( len ( p ) ) : NEW_LINE INDENT print ( p [ i ] , end = " ▁ " ) NEW_LINE DEDENT