再帰アルゴリズム——フィボナッチ数列を求める(1)


import java.util.Scanner;



/**

 * Created by Administrator on 14-5-13.

 *         

 *

 * Result M(Problem prob)

 {

 if (<problem can be solved easily>)

 return <easy solution>;

 // The problem cannot be solved easily.

 Problem smaller1 = <reduce problem to smaller problem>

 Result result1 = M(smaller1);

 Problem smaller2 = <reduce problem to smaller problem>

 Result result2 = M(smaller2);

 ...

 Result finalResult = <combine all results of smaller problem to solve large problem>

 return finalResult;

 }

 */

public class Fib {

    public static void main(String[] args){

        long startTime=System.currentTimeMillis();   //      

        int number=0;

        System.out.println("please give the number:");

        Scanner scanner=new Scanner(System.in);

        String str=scanner.nextLine();

        try{

            number=Integer.parseInt(str);

        }catch(NumberFormatException e){

            System.out.println("    ");

        }



        System.out.println(fac(number));

        long endTime=System.currentTimeMillis(); //      

        System.out.println("      : "+(endTime-startTime)+"ms");

    }

    public static int fac(int temp){

        if(temp<=2)

        {

            return 1;

        }

        else {

            return fac(temp-1)+fac(temp-2);

        }



    }

}