VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-prime-factors-and-their-powers/

⇱ Print all prime factors and their powers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all prime factors and their powers

Last Updated : 20 Mar, 2023

Given a number N, print all its unique prime factors and their powers in N. 

Examples: 

Input: N = 100
Output: Factor Power
 2 2
 5 2

Input: N = 35
Output: Factor Power
 5 1
 7 1


A Simple Solution is to first find prime factors of N. Then for every prime factor, find the highest power of it that divides N and print it.
An Efficient Solution is to use Sieve of Eratosthenes

1) First compute an array s[N+1] using Sieve of Eratosthenes.

s[i] = Smallest prime factor of "i" that
 divides "i".

For example let N = 10
 s[2] = s[4] = s[6] = s[8] = s[10] = 2;
 s[3] = s[9] = 3;
 s[5] = 5;
 s[7] = 7;


2) Using the above computed array s[],
 we can find all powers in O(Log N) time.

 curr = s[N]; // Current prime factor of N
 cnt = 1; // Power of current prime factor

 // Printing prime factors and their powers
 while (N > 1)
 {
 N /= s[N];

 // N is now N/s[N]. If new N also has its 
 // smallest prime factor as curr, increment 
 // power and continue
 if (curr == s[N])
 {
 cnt++;
 continue;
 }

 // Print prime factor and its power
 print(curr, cnt);

 // Update current prime factor as s[N] and
 // initializing count as 1.
 curr = s[N];
 cnt = 1;
 }

Below is the implementation of above steps.

Output: 
 

Factor Power
 2 3
 3 2
 5 1

Time Complexity: O(n*log(log(n)))
Auxiliary Space: O(n)

The above algorithm finds all powers in O(Log N) time after we have filled s[]. This can be very useful in competitive environment where we have an upper limit and we need to compute prime factors and their powers for many test cases. In this scenario, the array needs to be s[] filled only once.
 

Comment
Article Tags:
Article Tags: