栈的问题(非递归)

f(n)=1,当n=0时

f(n)=nf(n/2) 当n>0时

要求写出求f(n)的非递归算法

int f(int n)
{
 int st[MaxLen][3];
 int top=1;
 while(n>0)
 {
  st[top][2]=n;
  n=n/2;
  top++;
 }
 if(n==0)
 {
  st[top][1]=1;
 }
 while(top>1)
 {
  top--;
  st[top][3]=st[top+1][1];
  st[top][1]=st[top][2]*st[top][3];
 }
 return st[top][1];
}
void main()
{
 int n;
 cout<<"输入n"<<endl;
 cin>>n;
 cout<<"递归求解:F("<<n<<")="<<f(n)<<endl;
}

 

 

 

2.fn(x)=1 当n=0时

fn(x)=2x 当n=1时

fn(x)=2xfn-1(x)-2(n-1)fn-2(x) 当n>1时

要求编写出计算fn(x)值的非递归算法

double f(int n,double x)
{
 double st[MaxLen][2];
 int top=1;
 for(int i=n;i>=0;i--)
  st[top++][1]=i;
 st[--top][2]=1;
 st[--top][2]=2*x;
 top--;
 while(top>0)
 {
  st[top][2]=st[top+1][2]*2*x-2*st[top+1][1]*st[top+2][2];
  top--;
 }
 return st[1][2];

}
void main()
{
 double x;
 int n;
 cout<<"输入n,x"<<endl;;
 cin>>n>>x;
 cout<<"递归求解:F("<<n<<" "<<x<<")="<<f(n,x)<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值