用Java写ACM中的递归

问题 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);
	} 
}

猜你喜欢

转载自blog.csdn.net/weixin_37891342/article/details/85468565