Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • DSA
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Go Premium
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App

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

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Prerequisites : Sieve of Eratosthenes, Least prime factor of numbers till n.

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.


 


K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • sieve
  • prime-factor
Practice Tags :
  • Mathematical
  • sieve

Similar Reads

    Basics & Prerequisites

    Logic Building Problems
    Logic building is about creating clear, step-by-step methods to solve problems using simple rules and principles. It’s the heart of coding, enabling programmers to think, reason, and arrive at smart solutions just like we do.Here are some tips for improving your programming logic: Understand the pro
    2 min read
    Analysis of Algorithms
    Analysis of Algorithms is a fundamental aspect of computer science that involves evaluating performance of algorithms and programs. Efficiency is measured in terms of time and space.BasicsWhy is Analysis Important?Order of GrowthAsymptotic Analysis Worst, Average and Best Cases Asymptotic NotationsB
    1 min read

    Data Structures

    Array Data Structure
    In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
    3 min read
    String in Data Structure
    A string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
    2 min read
    Hashing in Data Structure
    Hashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
    2 min read
    Linked List Data Structure
    A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Here’s the comparison of Linked List vs Arrays Linked List:
    2 min read
    Stack Data Structure
    A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
    2 min read
    Queue Data Structure
    A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
    2 min read
    Tree Data Structure
    Tree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
    4 min read
    Graph Data Structure
    Graph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
    3 min read
    Trie Data Structure
    The Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
    15+ min read

    Algorithms

    Searching Algorithms
    Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
    2 min read
    Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
    Introduction to Recursion
    The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
    14 min read
    Greedy Algorithms
    Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
    3 min read
    Graph Algorithms
    Graph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
    3 min read
    Dynamic Programming or DP
    Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
    3 min read
    Bitwise Algorithms
    Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
    4 min read

    Advanced

    Segment Tree
    Segment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
    3 min read
    Pattern Searching
    Pattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
    2 min read
    Geometry
    Geometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
    2 min read

    Interview Preparation

    Interview Corner: All Resources To Crack Any Tech Interview
    This article serves as your one-stop guide to interview preparation, designed to help you succeed across different experience levels and company expectations. Here is what you should expect in a Tech Interview, please remember the following points:Tech Interview Preparation does not have any fixed s
    3 min read
    GfG160 - 160 Days of Problem Solving
    Are you preparing for technical interviews and would like to be well-structured to improve your problem-solving skills? Well, we have good news for you! GeeksforGeeks proudly presents GfG160, a 160-day coding challenge starting on 15th November 2024. In this event, we will provide daily coding probl
    3 min read

    Practice Problem

    GeeksforGeeks Practice - Leading Online Coding Platform
    GeeksforGeeks Practice is an online coding platform designed to help developers and students practice coding online and sharpen their programming skills with the following features. GfG 160: This consists of most popular interview problems organized topic wise and difficulty with with well written e
    6 min read
    Problem of The Day - Develop the Habit of Coding
    Do you find it difficult to develop a habit of Coding? If yes, then we have a most effective solution for you - all you geeks need to do is solve one programming problem each day without any break, and BOOM, the results will surprise you! Let us tell you how:Suppose you commit to improve yourself an
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Community
  • Videos
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • GATE
  • Software and Tools
  • Courses
  • IBM Certification
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • DSA 360
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences