试写出求递归函数F(n)的递归算法,并消除递归

2025-06-26 10:41:34
推荐回答(5个)
回答1:

你先了解这个函数的作用,结果就是 n*(n/(2^1)*(n/(2^2))*(n/(2^3))*(n/(2^4))……*1
n*(n/2)*(n/4)*(n/8)*……*1
while( n >= 0)
{
if(n !=0)
{ push();//将n压入栈内
n = n/2
}
else
{
push(n+1);//或者是push(1);
}
}
double result = 1;
while(栈不为空)
{
result = result * pop();//取出值并相乘
}
printf("%lf",result);

这个是伪代码哈,自己去实现

回答2:

递归就是本身调用自己。如n!=n(n-1)!,你定义函数f(n)=nf(n-1)而f(n-1)又是这个定义的函数。这就是递归。

实现递归。简单说来从未知的推到已知的
如:3!=3*2!
2!=2*1!
1!=1(已知的)

然后从已知再返回调用给上一层。到你所要求的
1!=1(已知)
2!=2*1!=2*1=2
3!=3*2!=3*2=6
递归结束

回答3:

//java代码

import java.util.Stack;

public class Test5 {
public static void main(String[] args) {
for(int n=0; n<=10; n++){
System.out.println("f(" + n + ")\t=\t" + f(n));
}
}

public static int f(int n){
if(n == 0){
return 1;
}
int value = 0;
Stack s = new Stack();
s.push(1); //f(0)入栈
for(int i=1; i<=n; i++){
//计算f(i)的值
value = i * Integer.parseInt(s.get(i/2).toString());
s.push(value); //f(i)入栈
}

return value;
}
}

回答4:

#include
#include
int main()
{
int x;
scanf("%d",&x);
if(x<0)
{
printf("输入错误!程序结束\n");
exit(0);
}
int result=1;
while(x>0)
{
result*=x;
x/=2;
}
printf("F(%d)=%d",x,result);
return 0;
}

回答5:

第二个式子F(n) = nF(n/2),(n>0),其中的n/2是指整除还是实除?如果实除的话,对于大于0的n,递归都不会终止。