VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-prime-factors-of-a-given-integer-in-decreasing-order-using-stack/

⇱ Print prime factors of a given integer in decreasing order using Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print prime factors of a given integer in decreasing order using Stack

Last Updated : 23 Jul, 2025

Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure.

Examples:

Input: N = 34
Output:
17 2
Explanation:
The prime factors of the number 34 is 2 and 17.

Input: N = 8
Output: 2

Approach: The idea is to use the Stack data structure to store all the prime factors of N and in the end, print all the values in the Stack. Follow the steps below to solve the problem:

  1. Initialize a stack, say st.
  2. Run a loop while N != 1. From i = 2, for each value of i, run a loop until N % i == 0 and push i into the stack st and update N to N/i.
  3. Finally, print all the values from top to bottom of stack st.

Below is the implementation of the above approach:


Output: 
2

 

Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)

Comment
Article Tags: