首页 > 代码库 > 递归算法——求取斐波那契数列(1)
递归算法——求取斐波那契数列(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); } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。