天天看點

Java每日一題(2)

 題目: 請用程式分别實作遞和歸疊代算法。   答: == 遞歸 ==  

package com.test;

public class CallSelf {

   public static void main(String[] args) {

     // int

     int number=4;

     // call sum    

    System.out.println( "sum("+number+ ")="+sum(number));

     // call getFactorial

    System.out.println( "getFactorial("+number+ ")="+getFactorial(number));

  }

   public static int sum( int x){

     //break

     if(x<=0){

       return x;

    }

     //call self & sum up

     int total=x+sum(x-1);

     return total;

  }

   public static int getFactorial( int x){

     //condition

     if(x==1){

       return 1;

    }

     //call self & get factorical

     return x*getFactorial(x-1);

  }

}

  == 疊代 ==     

         public static int    feibo( int n)        

        {        

                     int    start1 = 1;        

                     int start2 = 1;        

                     for( int i = 2; i < n; i++)        

                    {        

                             int temp = start1+start2;        

                             start1 = start2;        

                             start2 = temp;        

                    }        

                     return start2;        

        }        

轉載于:https://blog.51cto.com/danni505/203648