1. 程式人生 > >猴子分桃二採用遞迴的方式

猴子分桃二採用遞迴的方式

<span style="font-size:18px;">package lianx;


public class MonKeyTao {


	static int ts=0;//桃子總數
    int fs=1;//記錄分的次數
    static int hs=5;//猴子數...
    int tsscope=5000;//桃子數的取值範圍.太大容易溢位.
    public int fT(int t){
        if(t==tsscope){
            //當桃子數到了最大的取值範圍時取消遞迴
            System.out.println("結束");
           return 0;
        }else{
            if((t-1)%hs==0 && fs <=hs){
                if(fs==hs){
                    System.out.println("桃子數 = "+ts +" 時滿足分桃條件");
                }
                fs+=1;
                return fT((t-1)/5*4);// 返回猴子拿走一份後的剩下的總數
            }else{
                //沒滿足條件
               fs=1;//分的次數重置為1
               return fT(ts+=1);//桃子數加+1
        }
      }
    }
    public static void main(String[] args) {
        new MonKeyTao().fT(0);
    }
}</span>