用Java写ACM中的递归

本文详细解析了一个简单的递归问题,定义了一个递归函数f(n),并提供了完整的Java实现代码。函数根据不同条件进行计算:当n为0或1时,f(n)=1;当n为偶数时,f(n)=2*f(n-1);其他情况下,f(n)=f(n-1)+f(n-2)。文章包括了输入输出示例,适合初学者理解和实践递归算法。

问题 E: A simple recursion problem

题目描述

We have a simple task for you. A recursive function f(n) is defined as: when n=0 or n=1, f(n)=1; and n%2=0, f(n)=2*f(n-1); and f(n)= f(n-1)+f(n-2) otherwise. It is an easy recursive function to implement, isn’t it? Write a program and get your AC!!

输入

There are multiple test cases in the input. An integer n (0<=n<=10) is given in a single line for each case. You need to process the end of file.

输出

For each case, output the value of the f(n) in the format ”fn=d” in a single line.

样例输入

0

1

2

3

样例输出

f0=1

f1=1

f2=2

f3=3

/* when n=0 or n=1, f(n)=1; 
 * and n%2=0, f(n)=2*f(n-1); 2的倍数就。。。
 * and f(n)= f(n-1)+f(n-2)   单数就等于前两个函数的和
 * */
import java.util.Scanner;
public class E {
	public static void main(String[] args) {
		 Scanner in = new Scanner(System.in);
	     int num,result;
	     while(in.hasNext())           //没说按0结束都要这样判断
	     {    
	    	  num = Integer.parseInt(in.nextLine());
	    	  result = f(num);
	    	  System.out.println("f"+num+"="+result);
	     }
	}
	public static int f(int n){
		if(n==0 || n==1)
		   return 1;
		else if(n%2==0)
		   return 2*f(n-1);
		else
		   return f(n-1)+f(n-2);
	} 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值