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;
}