Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • 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
      • Data Science Training Program
      • 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
  • 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
Next Article:
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
Next article icon

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

Last Updated : 14 Aug, 2024
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.


 


Next Article
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range

N

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

Similar Reads

    Check for Prime Number
    Given a number n, check whether it is a prime number or not.Note: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.Input: n = 7Output: trueExplanation: 7 is a prime number because it is greater than 1 and has no divisors other than 1 and itself.Input: n
    11 min read

    Primality Test Algorithms

    Introduction to Primality Test and School Method
    Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: trueInput: n = 15Output: falseInput: n = 1Output:
    10 min read
    Fermat Method of Primality Test
    Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Introduction to Primality Test and School MethodIn this post, Fermat's method is discussed. This method is a probabilistic method and is based on Fermat's Little Theorem.
    10 min read
    Primality Test | Set 3 (Miller–Rabin)
    Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabili
    15+ min read
    Solovay-Strassen method of Primality Test
    We have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (Miller–Rabin)The Solovay–Strassen test is a probabilistic algorithm used to check if a number is prime
    13 min read
    Lucas Primality Test
    A number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermat’s Little Theorem: If p is prime and
    12 min read
    Sieve of Eratosthenes
    Given a number n, find all prime numbers less than or equal to n.Examples:Input: n = 10Output: [2, 3, 5, 7]Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are [2, 3, 5, 7].Input: n = 35Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]Explanation: The prime numbers up to 35 o
    5 min read
    How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
    Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime an
    3 min read
    Sieve of Eratosthenes in 0(n) time complexity
    The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.Example : Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input :
    12 min read

    Programs and Problems based on Sieve of Eratosthenes

    C++ Program for Sieve of Eratosthenes
    Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19".CPP// C++ program to print all primes smaller than or equal to // n usin
    2 min read
    Java Program for Sieve of Eratosthenes
    Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be "2, 3, 5, 7". If n is 20, the output should be "2, 3, 5, 7, 11, 13, 17, 19". Java // Java program to print all primes smaller than or equal to // n
    2 min read
    Scala | Sieve of Eratosthenes
    Eratosthenes of Cyrene was a Greek mathematician, who discovered an amazing algorithm to find prime numbers. This article performs this algorithm in Scala. Step 1 : Creating an Int Stream Scala 1== def numberStream(n: Int): Stream[Int] = Stream.from(n) println(numberStream(10)) Output of above step
    4 min read
    Check if a number is Primorial Prime or not
    Given a positive number N, the task is to check if N is a primorial prime number or not. Print 'YES' if N is a primorial prime number otherwise print 'NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# - 1 , where pn# is the primorial of pn i.e the pro
    10 min read
    Sum of all Primes in a given range using Sieve of Eratosthenes
    Given a range [l, r], the task is to find the sum of all the prime numbers in the given range from l to r both inclusive.Examples: Input : l = 10, r = 20Output : 60Explanation: Prime numbers between [10, 20] are: 11, 13, 17, 19Therefore, sum = 11 + 13 + 17 + 19 = 60Input : l = 15, r = 25Output : 59E
    1 min read
    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
    11 min read
    Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range
    A number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so. Example: Input : from = 1, to = 20 Out
    3 min read
    Segmented Sieve
    Given a number n, print all primes smaller than n. Input: N = 10Output: 2, 3, 5, 7Explanation : The output “2, 3, 5, 7” for input N = 10 represents the list of the prime numbers less than or equal to 10. Input: N = 5Output: 2, 3, 5 Explanation : The output “2, 3, 5” for input N = 5 represents the li
    15+ min read
    Segmented Sieve (Print Primes in a Range)
    Given a range [low, high], print all primes in this range? For example, if the given range is [10, 20], then output is 11, 13, 17, 19. A Naive approach is to run a loop from low to high and check each number for primeness. A Better Approach is to precalculate primes up to the maximum limit using Sie
    15 min read
    Longest sub-array of Prime Numbers using Segmented Sieve
    Given an array arr[] of N integers, the task is to find the longest subarray where all numbers in that subarray are prime. Examples: Input: arr[] = {3, 5, 2, 66, 7, 11, 8} Output: 3 Explanation: Maximum contiguous prime number sequence is {2, 3, 5} Input: arr[] = {1, 2, 11, 32, 8, 9} Output: 2 Expla
    13 min read
    Sieve of Sundaram to print all primes smaller than n
    Given a number n, print all primes smaller than or equal to n.Examples: Input: n = 10Output: 2, 3, 5, 7Input: n = 20Output: 2, 3, 5, 7, 11, 13, 17, 19We have discussed Sieve of Eratosthenes algorithm for the above task. Below is Sieve of Sundaram algorithm.printPrimes(n)[Prints all prime numbers sma
    10 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
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@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