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:
- 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++
#include <bits/stdc++.h>
using namespace std;
void PrimeFactors( int N)
{
stack< int > st;
int i = 2;
while (N != 1) {
if (N % i == 0) {
st.push(i);
while (N % i == 0) {
N = N / i;
}
}
i++;
}
while (!st.empty()) {
printf ( "%d " , st.top());
st.pop();
}
}
int main()
{
int N = 8;
PrimeFactors(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void PrimeFactors( int N)
{
Stack<Integer> st = new Stack<>();
int i = 2 ;
while (N != 1 )
{
if (N % i == 0 )
{
st.push(i);
while (N % i == 0 )
{
N = N / i;
}
}
i++;
}
while (!st.isEmpty())
{
System.out.println(st.peek());
st.pop();
}
}
public static void main (String[] args)
{
int N = 8 ;
PrimeFactors(N);;
}
}
|
Python3
def PrimeFactors(N):
st = []
i = 2
while (N ! = 1 ):
if (N % i = = 0 ):
st.append(i)
while (N % i = = 0 ):
N = N / / i
i + = 1
while ( len (st) ! = 0 ):
print (st[ - 1 ])
st.pop()
if __name__ = = "__main__" :
N = 8
PrimeFactors(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void PrimeFactors( int N)
{
Stack< int > st = new Stack< int >();
int i = 2;
while (N != 1)
{
if (N % i == 0)
{
st.Push(i);
while (N % i == 0)
{
N = N / i;
}
}
i++;
}
while (st.Count != 0)
{
Console.Write(st.Peek());
st.Pop();
}
}
public static void Main ()
{
int N = 8;
PrimeFactors(N);;
}
}
|
Javascript
<script>
function PrimeFactors(N)
{
let st = [];
let i = 2;
while (N != 1)
{
if (N % i == 0)
{
st.push(i);
while (N % i == 0)
{
N = Math.floor(N / i);
}
}
i++;
}
while (st.length!=0)
{
document.write(st.pop());
}
}
let N = 8;
PrimeFactors(N);
</script>
|
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)