求一个树的质数因子,按降序排列
#include<iostream>#define maxsize 100
using namespace std;
typedef struct
{
int data[maxsize];
int top;
}seqstack;
seqstack *init_seqstack()//栈的初始化
{
seqstack *s;
s=new seqstack;
s->top=-1;
return s;
}
void push_seqstack(seqstack *s,int x)//入栈算法
{
if(s->top==maxsize-1)
cout<<"error";
else
{
++s->top;
s->data[s->top]=x;
}
}
void pop_seqstack(seqstack *s)//出栈算法,该函数输出堆栈里的所有元素,而不是一个元素
{
int x;
while(s->top!=-1)
{
x=s->data[s->top];
s->top--;
cout<<x<<" ";//每输出一个元素打印一个空格
}
}
int small_yinsu(int x)//取任意一个数的最小因子,返回该因子
{
int d=2;
while(x%d!=0)
d++;
return d;
}
seqstack *yinzi(int y)//求一个数的质数分解,压入堆栈,该函数调用small_yinsu(int x)
{
int m=y;
seqstack *s;
s=init_seqstack();//初始化堆栈
while(m!=1)
{
push_seqstack(s,small_yinsu(m));//调用small_yinsu(int x)
m=m/small_yinsu(m);//每得到一个因子,将改变目标数值
}
return s;//返回存有所有质数因子的堆栈
}
void main()
{
cout<<"Enter a positive integer (0 to stop): ";
int z;
cin>>z;//输入一个将要求质数因子的数
while(z>0)//输入非正数作为结束条件
{
pop_seqstack(yinzi(z));
cout<<endl<<"Enter a positive integer (0 to stop): ";
cin>>z;
if(z<=0)//如果输入非正数,显示error
cout<<"Errors! "<<z<<" is not a positive integer ";
}
}