用栈来实现分解一个数成素因子乘积的形式。

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

stack.h源文件:

#include <math.h>

#include <iostream.h>

const int maxentry=20;

enum error_code{fail,success,overflow,underflow};

template<class type>

class stack

{

private:

int count;

type entry[maxentry];

public:

stack()

{count=0;}

error_code push(const type &a);

error_code pop();

bool empty()const;

error_code top(type &a)const;

int numbers();

};

template<class type>

error_code stack<type>::push(const type &a)

{

error_code outcome=success;

if(count<maxentry)

{

entry[count++]=a;

}

else outcome=fail;

return outcome;

}

template<class type>

error_code stack<type>::pop()

{

error_code outcome=success;

if(count>0)

{

count--;

}

else outcome=fail;

return outcome;

}

template<class type>

bool stack<type>::empty() const

{

return count==0;

}

template<class type>

error_code stack<type>::top(type &a) const

{

error_code outcome=success;

if(count>0)

{

a=entry[count-1];

}

else outcome=fail;

return outcome;

}

template<class type>

int stack<type>::numbers()

{

return count;

}

bool isprime(int n)

{

if (n==1)

return false;

int k;

k=sqrt(n);

for (int i=2;i<=k;i++)

{

if (n%i==0)

{return false;}

if (i>=k+1)

{return true;}

else {return false;}

}

}

void prime(stack<int> num)

{

int m=2;

//int a[255]={0,};

//int i;

int n;

num.top(n);

//num.pop();

//cout<<n<<endl;

if (n==1||n==0||n<0)

{cout<<"您所输入的数没有素因子。"<<endl;return;}

while (n>1)

{

loop1:{

if (isprime(n))

{goto loop2;}

else if (n%m==0)

{

//cout<<num.top()<<endl;

num.pop();

n=n/m;

num.push(m);

if (n!=1)

num.push(n);

goto loop1;

}

else m++;

if (!isprime(m))

m++;

else goto loop1;

}

}

/*if (num.top(i)==1)

num.pop();*/

loop2:{ int x=num.numbers();

for (int j=0;j<=x-1;j++)

{

int m;

num.top(m);

cout<<m<<" ";

num.pop();

}

cout<<endl;

}

}

prime.cpp:

#include <iostream>

using namespace std;

#include "stack.h"

#include <math.h>

void prime(stack<int>);

bool isprime(int);

void main()

{

stack<int> num;

int n;

char s;

loop1:{cout<<"Input a Number:"<<endl;

cin>>n;

cout<<"The prime of the number is:"<<endl;

//cout<<isprime(n)<<endl;

num.push(n);

prime(num);}

cout<<"是否继续?"<<endl;

cin>>s;

if (s=='y')

{num.pop();

goto loop1;}

else return;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有