Prime Factorization using Sieve O(log n) for multiple queries

We can calculate the prime factorization of a number “n” in O(sqrt(n)) as discussed here. But O(sqrt n) method times out when we need to answer multiple queries regarding prime factorization.
In this article, we study an efficient method to calculate the prime factorization using O(n) space and O(log n) time complexity with pre-computation allowed.

Recommended Practice

Approach: 

The main idea is to precompute the Smallest Prime Factor (SPF) for each number from 1 to MAXN using the sieve function. SPF is the smallest prime number that divides a given number without leaving a remainder. Then, the getFactorization function uses the precomputed SPF array to find the prime factorization of the given number by repeatedly dividing the number by its SPF until it becomes 1.

To calculate to smallest prime factor for every number we will use the sieve of eratosthenes. In the 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).

Now, after we are done with precalculating the smallest prime factor for every number we will divide our number n (whose prime factorization is to be calculated) by its corresponding smallest prime factor till n becomes 1. 

Pseudo Code for prime factorization assuming
SPFs are computed :

PrimeFactors[] // To store result

i = 0 // Index in PrimeFactors

while n != 1 :

// SPF : smallest prime factor
PrimeFactors[i] = SPF[n]
i++
n = n / SPF[n]

Step-by-step approach of above idea:

  • Defines a constant MAXN equal to 100001.
  • An integer array spf of size MAXN is declared. This array will store the smallest prime factor for each number up to MAXN.
  • A function sieve() is defined to calculate the smallest prime factor of every number up to MAXN using the Sieve of Eratosthenes algorithm.
  • The smallest prime factor for the all the number is initially set to 1.
  • If a number i is prime, then the smallest prime factor for all numbers divisible by i and if their smallest prime factor hasnt been found yet is then set to i.
  • A function getFactorization(int x) is defined to return the prime factorization of a given integer x using the spf array.
  • The getFactorization(int x) function finds the smallest prime factor of x, pushes it to a vector, and updates x to be the quotient of x divided by its smallest prime factor. This process continues until x becomes 1, at which point the vector of prime factors is returned.
  • In the main() function, the sieve() function is called to precalculate the smallest prime factor of every number up to MAXN. Then, the prime factorization of a sample integer x is found using the getFactorization(int x) function, and the result is printed to the console.

The implementation for the above method is given below : 

C++
// C++ program to find prime factorization of a
// number n in O(Log n) time with precomputation
// allowed.
#include "bits/stdc++.h"
using namespace std;

#define MAXN 100001
vector<int> spf(MAXN + 1, 1);

// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
void sieve()
{
    // stores smallest prime factor for every number

    spf[0] = 0;
    for (int i = 2; i <= MAXN; i++) {
        if (spf[i] == 1) { // if the number is prime ,mark
                           // all its multiples who havent
                           // gotten their spf yet
            for (int j = i; j <= MAXN; j += i) {
                if (spf[j]== 1) // if its smallest prime factor is
                          // 1 means its spf hasnt been
                          // found yet so change it to i
                    spf[j] = i;
            }
        }
    }
}

// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
vector<int> getFactorization(int x)
{
    vector<int> ret;
    while (x != 1) {
        ret.push_back(spf[x]);
        x = x / spf[x];
    }
    return ret;
}

// driver program for above function
int main(int argc, char const* argv[])
{
    // precalculating Smallest Prime Factor
    sieve();
    int x = 12246;
    cout << "prime factorization for " << x << " : ";

    // calling getFactorization function
    vector<int> p = getFactorization(x);

    for (int i = 0; i < p.size(); i++)
        cout << p[i] << " ";
    cout << endl;
    return 0;
}
//This code has been contributed ny narayan95
Java
// Java program to find prime factorization of a
// number n in O(Log n) time with precomputation
// allowed.

import java.util.Vector;

class Test {
    static final int MAXN = 100001;

    // stores smallest prime factor for every number
    static int spf[] = new int[MAXN];

    // Calculating SPF (Smallest Prime Factor) for every
    // number till MAXN.
    // Time Complexity : O(nloglogn)
    static void sieve()
    {
        spf[0] = 0;
        spf[1] = 1;
        for (int i = 2; i < MAXN; i++) {
            // marking smallest prime factor for every
            // number to be 1.
            spf[i] = 1;
        }
        for (int i = 2; i < MAXN; i++) {
            if (spf[i] == 1) { // if the number is prime ,mark
                               // all its multiples who havent
                               // gotten their spf yet
                for (int j = i; j < MAXN; j += i) {
                    spf[j] = i;// if its smallest prime factor is
                                       // 1 means its spf hasnt been
                                       // found yet so change its spf to i
                }
            }
        }
    }

    // A O(log n) function returning primefactorization
    // by dividing by smallest prime factor at every step
    static Vector<Integer> getFactorization(int x)
    {
        Vector<Integer> ret = new Vector<>();
        while (x != 1) {
            ret.add(spf[x]);
            x = x / spf[x];
        }
        return ret;
    }

    // Driver method
    public static void main(String args[])
    {
        // precalculating Smallest Prime Factor
        sieve();
        int x = 12246;
        System.out.print("prime factorization for " + x
                         + " : ");

        // calling getFactorization function
        Vector<Integer> p = getFactorization(x);

        for (int i = 0; i < p.size(); i++)
            System.out.print(p.get(i) + " ");
        System.out.println();
    }
}
//This code is contributed by narayan95
Python
# Python3 program to find prime factorization
# of a number n in O(Log n) time with
# precomputation allowed.
import math as mt

MAXN = 100001

# stores smallest prime factor for
# every number = 1
spf = [1] * (MAXN + 1)
# Calculating SPF (Smallest Prime Factor)
# for every number till MAXN.
# Time Complexity : O(nloglogn)


def sieve():
    spf[0] = 0
    for i in range(2, MAXN + 1):
        if spf[i] == 1:  # if the number is prime, mark
                         # all its multiples who havent
                         # gotten their spf yet
            for j in range(i, MAXN + 1, i):
                if spf[j] == 1:  # if its smallest prime factor is
                                 # 1 means its spf hasnt been
                                 # found yet so change it to i
                    spf[j] = i

# A O(log n) function returning prime
# factorization by dividing by smallest
# prime factor at every step


def getFactorization(x):
    ret = list()
    while (x != 1):
        ret.append(spf[x])
        x = x // spf[x]

    return ret

# Driver code


# precalculating Smallest Prime Factor
sieve()
x = 12246
print("prime factorization for", x, ": ",
      end="")

# calling getFactorization function
p = getFactorization(x)

for i in range(len(p)):
    print(p[i], end=" ")

# This code is contributed
# by narayan95
C#
// C# program to find prime factorization of a
// number n in O(Log n) time with precomputation
// allowed.
using System;
using System.Collections;

class GFG {
    static int MAXN = 100001;

    // stores smallest prime factor for every number
    static int[] spf = new int[MAXN];

    // Calculating SPF (Smallest Prime Factor) for every
    // number till MAXN.
    // Time Complexity : O(nloglogn)
    static void sieve()
    {
        spf[0] = 0;
        spf[1] = 1;
        for (int i = 2; i < MAXN; i++) {
            // marking smallest prime factor for every
            // number = 1.
            spf[i] = 1;
        }
        for (int i = 2; i < MAXN; i++) {
            if (spf[i]== 1) { // if the number is prime ,mark
                        // all its multiples who havent
                        // gotten their spf yet
                for (int j = i; j < MAXN; j += i) {
                    if (spf[j]== 1) { // if its smallest prime
                                // factor is 1 means its spf
                                // hasnt been found yet so
                                // change it to i
                        spf[j] = i;
                    }
                }
            }
        }
    }

    // A O(log n) function returning primefactorization
    // by dividing by smallest prime factor at every step
    static ArrayList getFactorization(int x)
    {
        ArrayList ret = new ArrayList();
        while (x != 1) {
            ret.Add(spf[x]);
            x = x / spf[x];
        }
        return ret;
    }

    // Driver code
    public static void Main()
    {
        // precalculating Smallest Prime Factor
        sieve();
        int x = 12246;
        Console.Write("prime factorization for " + x
                      + " : ");

        // calling getFactorization function
        ArrayList p = getFactorization(x);

        for (int i = 0; i < p.Count; i++)
            Console.Write(p[i] + " ");
        Console.WriteLine("");
    }
}

// This code is contributed by narayan95
Javascript
<script>
// Javascript program to find prime factorization of a
// number n in O(Log n) time with precomputation
// allowed.

const MAXN = 100001;
let spf = new Array(MAXN + 1).fill(1);

// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)

function sieve() {
    // stores smallest prime factor for every number
    spf[0] = 0;
    for (let i = 2; i <= MAXN; i++) {
        if (spf[i] === 1) { // if the number is prime ,mark
                            // all its multiples who havent
                            // gotten their spf yet
            for (let j = i; j <= MAXN; j += i) {
                if (spf[j] === 1) { // if its smallest prime factor is
                                   // 1 means its spf hasnt been
                                   // found yet so change it to i
                    spf[j] = i;
                }
            }
        }
    }
}
  
    // A O(log n) function returning primefactorization
    // by dividing by smallest prime factor at every step
    function getFactorization(x)
    {
        let ret =[];
        while (x != 1)
        {
            ret.push(spf[x]);
            x = Math.floor(x / spf[x]);
        }
        return ret;
    }
    
    // Driver method
    
    // precalculating Smallest Prime Factor
    sieve();
    let x = 12246;
    document.write("prime factorization for " + x + " : ");
    // calling getFactorization function
    let  p = getFactorization(x);
    for (let i=0; i<p.length; i++)
            document.write(p[i] + " ");
        document.write("<br>");
    
// This code is contributed by narayan95
</script>
PHP
<?php
// PHP program to find prime factorization 
// of a number n in O(Log n) time with 
// precomputation allowed.
define("MAXN", 100001);
$spf = array_fill(0, MAXN + 1, 1);

// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
function sieve() {
    global $spf;

    // stores smallest prime factor for every number
    $spf[0] = 0;
    for ($i = 2; $i <= MAXN; $i++) {
        if ($spf[$i] == 1) { // if the number is prime ,mark
                             // all its multiples who havent
                             // gotten their spf yet
            for ($j = $i; $j <= MAXN; $j += $i) {
                if ($spf[$j] == 1) { // if its smallest prime factor is
                                     // 1 means its spf hasnt been
                                     // found yet so change it to i
                    $spf[$j] = $i;
                }
            }
        }
    }
}

// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
function getFactorization($x)
{
    global $spf;
    $ret = array();
    while ($x != 1)
    {
        array_push($ret, $spf[$x]);
        if($spf[$x])
        $x = (int)($x / $spf[$x]);
    }
    return $ret;
}

// Driver Code

// precalculating Smallest 
// Prime Factor
sieve();
$x = 12246;
echo "prime factorization for " .
                      $x . " : ";

// calling getFactorization function
$p = getFactorization($x);

for ($i = 0; $i < count($p); $i++)
    echo $p[$i] . " ";

// This code is contributed by narayan95
?>

Output: 

prime factorization for 12246 : 2 3 13 157

Time Complexity: O(log n), for each query (Time complexity for precomputation is not included)
Auxiliary Space: O(1)

Note : The above code works well for n upto the order of 10^7. Beyond this we will face memory issues.

Time Complexity: The precomputation for smallest prime factor is done in O(n log log n) using sieve. Whereas in the calculation step we are dividing the number every time by the smallest prime number till it becomes 1. So, let’s consider a worst case in which every time the SPF is 2 . Therefore will have log n division steps. Hence, We can say that our Time Complexity will be O(log n) in worst case.


 



Contact Us