demo01.java
package com.sjjg;
public class demo01 {
/* 0 1 2 3 4 5
* 0 1 1 2 3 5 8 13 ....
*/
// O(2^n)
public static int fib1(int n) {
if (n <= 1) return n;
return fib1(n - 1) + fib1(n - 2);
}
// O(n)
public static int fib2(int n) {
if (n <= 1) return n;
int first = 0;
int second = 1;
for (int i = 0; i < n - 1; i++) {
int sum = first + second;
first = second;
second = sum;
}
return second;
}
public static int fib3(int n) {
if (n <= 1) return n;
int first = 0;
int second = 1;
while (n-- > 1) {
second += first;
first = second - first;
}
return second;
}
public static void main(String[] args) {
int n = 45;
// System.out.println(fib2(70));
//System.out.println(fib3(n));
TimeTool.test("fib1", new TimeTool.Task() {
public void execute() {
System.out.println(fib1(n));
}
});
TimeTool.test("fib2", new TimeTool.Task() {
public void execute() {
System.out.println(fib2(n));
}
});
}
}
输出:
【fib1】
开始:16:04:31.033
1134903170
结束:16:04:35.223
耗时:4.19秒
-------------------------------------
【fib2】
开始:16:04:35.224
1134903170
结束:16:04:35.224
耗时:0.0秒
-------------------------------------
进程已结束,退出代码 0
package com.sjjg;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeTool {
private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss.SSS");
public interface Task {
void execute();
}
public static void test(String title, Task task) {
if (task == null) return;
title = (title == null) ? "" : ("【" + title + "】");
System.out.println(title);
System.out.println("开始:" + fmt.format(new Date()));
long begin = System.currentTimeMillis();
task.execute();
long end = System.currentTimeMillis();
System.out.println("结束:" + fmt.format(new Date()));
double delta = (end - begin) / 1000.0;
System.out.println("耗时:" + delta + "秒");
System.out.println("-------------------------------------");
}
}