给定整数N ,任务是使用堆栈数据结构以降序打印N的素因数。
例子:
Input: N = 34
Output:
17 2
Explanation:
The prime factors of the number 34 is 2 and 17.
Input: N = 8
Output: 2
方法:想法是使用Stack数据结构存储N的所有素数,最后打印出Stack中的所有值。请按照以下步骤解决问题:
- 初始化堆栈,说st 。
- 在N!= 1时运行循环。从i = 2开始,对于i的每个值,循环运行直到N%i == 0并将i推入堆栈st并将N更新为N / i。
- 最后,从堆栈st的顶部到底部打印所有值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to print prime factors
// of N in decreasing order
void PrimeFactors(int N)
{
// Stores prime factors of N
// in decreasing order
stack 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 Code
int main()
{
int N = 8;
// function Call
PrimeFactors(N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to print prime factors
// of N in decreasing order
static void PrimeFactors(int N)
{
// Stores prime factors of N
// in decreasing order
Stack 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
# Python3 program for the above approach
# Function to print prime factors
# of N in decreasing order
def 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 Code
if __name__ == "__main__":
N = 8
# function Call
PrimeFactors(N)
# This code is contributed by chitranayal.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print prime factors
// of N in decreasing order
static void PrimeFactors(int N)
{
// Stores prime factors of N
// in decreasing order
Stack 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.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
输出:
2
时间复杂度: O(sqrt(N))
辅助空间: O(1)