2018-母牛的故事(java)

在这里插入图片描述
思路:这是一道类似于斐波那契数列的找规律题,解决的方法可采用递归,fn=f(n-1)+f(n-3)。
规律的解释:f(n-1)求的是去年牛的总数,f(n-3)求的是今年生下新小牛的数量。( 因为小母牛第四年才可以具有生殖能力,所以要往前推三年,才可求出今年可以生出新小牛的数量。)

import java.util.*;
public class Main 
{
    
    
	
	public static void main(String[] args) 
	{
    
    
		Scanner a=new Scanner(System.in);
		while(a.hasNext())
		{
    
    
		int n=a.nextInt();
		int sum=0;
		if(n==0)
			break;
		else if(n>0&&n<55)
			{
    
    
			 System.out.println(Add(n));
			}
		}
	}
	static int Add(int n) //总数=去年总数+能生育小牛的母牛
	{
    
    
		if(n==1)
			return 1;
		else if(n==2)
			return 2;
		else if(n==3)
			return 3;
		return Add(n-1)+Add(n-3);
	}
}

若有错误,还请指正

猜你喜欢

转载自blog.csdn.net/weixin_45956604/article/details/113757113