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

18 Jun, 2021
Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure.
Examples:
Input: N = 34Output:17 2Explanation:The prime factors of the number 34 is 2 and 17.
Input: N = 8Output: 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:
Initialize a stack, say st.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.Finally, print all the values from top to bottom of stack st.
Initialize a stack, say st.
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.
Finally, print all the values from top to bottom of stack st.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print prime factors// of N in decreasing ordervoid PrimeFactors(int N){    // Stores prime factors of N    // in decreasing order    stack<int> st;     int i = 2;    while (N != 1) {         if (N % i == 0) {             // Insert i into stack            st.push(i);             while (N % i == 0) {                 // Update N                N = N / i;            }        }         // Update i        i++;    }     // Print value of stack st    while (!st.empty()) {         printf("%d ", st.top());        st.pop();    }} // Driver Codeint main(){    int N = 8;     // function Call    PrimeFactors(N);    return 0;}
// Java program for the above approach import java.util.*; class GFG{         // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){         // Stores prime factors of N    // in decreasing order    Stack<Integer> st = new Stack<>();     int i = 2;         while (N != 1)    {        if (N % i == 0)        {                         // Insert i into stack            st.push(i);             while (N % i == 0)            {                                 // Update N                N = N / i;            }        }         // Update i        i++;    }     // Print value of stack st    while (!st.isEmpty())    {        System.out.println(st.peek());        st.pop();    }} // Driver Code   public static void main (String[] args)   {       int N = 8;         // Function Call    PrimeFactors(N);;}} // This code is contributed by susmitakundugoaldanga
# Python3 program for the above approach # Function to print prime factors# of N in decreasing orderdef PrimeFactors(N):     # Stores prime factors of N    # in decreasing order    st = []    i = 2    while (N != 1):        if (N % i == 0):             # Insert i into stack            st.append(i)            while (N % i == 0):                 # Update N                N = N // i         # Update i        i += 1     # Print value of stack st    while (len(st) != 0):        print(st[-1])        st.pop() # Driver Codeif __name__ == "__main__":    N = 8     # function Call    PrimeFactors(N)     # This code is contributed by chitranayal.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{         // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){         // Stores prime factors of N    // in decreasing order    Stack<int> st = new Stack<int>();     int i = 2;         while (N != 1)    {        if (N % i == 0)        {                         // Insert i into stack            st.Push(i);             while (N % i == 0)            {                                 // Update N                N = N / i;            }        }         // Update i        i++;    }     // Print value of stack st    while (st.Count != 0)    {        Console.Write(st.Peek());        st.Pop();    }} // Driver Code   public static void Main ()   {      int N = 8;         // Function Call    PrimeFactors(N);;}} // This code is contributed by code_hunt
<script> // JavaScript program for the above approach // Function to print prime factors// of N in decreasing orderfunction PrimeFactors(N){    // Stores prime factors of N    // in decreasing order    let st = [];      let i = 2;          while (N != 1)    {        if (N % i == 0)        {                          // Insert i into stack            st.push(i);              while (N % i == 0)            {                                  // Update N                N = Math.floor(N / i);            }        }          // Update i        i++;    }      // Print value of stack st    while (st.length!=0)    {        document.write(st.pop());             }}// Driver Code  let N = 8;      // Function CallPrimeFactors(N);  // This code is contributed by avanitrachhadiya2155 </script>
2
 
Time Complexity: O(sqrt(N))Auxiliary Space: O(1)
ukasp
susmitakundugoaldanga
code_hunt
avanitrachhadiya2155
cpp-stack-functions
prime-factor
Mathematical
Searching
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
How to check if a given point lies inside or outside a polygon?
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number