# Java与算法之(3) - 斐波那契数列

1+1=2

1+2=3

2+3=5

3+5=8

5+8=13

public class Fibonacci {
public static long calc(long n) {
if(n < 0) {
return 0;
}
if(n == 0 || n == 1) {
return n;
} else {
return calc(n - 1) + calc(n - 2);
}
}
}

    public static void main(String[] args) {
long n = 50;
long begin = System.nanoTime();
long f = Fibonacci.calc(n);
long end = System.nanoTime();
System.out.println("第" + n + "个斐波那契数是" + f + ", 耗时" + TimeUnit.NANOSECONDS.toMillis(end - begin) + "毫秒");
}

第50个斐波那契数是12586269025, 耗时66024毫秒

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Fibonacci extends RecursiveTask<Long> {

long n;
public Fibonacci(long n) {
this.n = n;
}

public Long compute() {
if(n <= 10) {  //小于10不再分解
return Fibonacci.calc(n);
}
Fibonacci f1 = new Fibonacci(n - 1);  //分解出计算n-1斐波那契数的子任务
f1.fork();  //由ForkJoinPool分配线程执行子任务
Fibonacci f2 = new Fibonacci(n - 2);  //分解出计算n-2斐波那契数的子任务
return f2.compute() + f1.join();
}

public static long calc(long n) {
if(n < 0) {
return 0;
}
if(n == 0 || n == 1) {
return n;
} else {
return calc(n - 1) + calc(n - 2);
}
}

public static void main(String[] args) {
long n = 50;
long begin = System.nanoTime();
Fibonacci fibonacci = new Fibonacci(n);
ForkJoinPool pool = new ForkJoinPool();
long f = pool.invoke(fibonacci);
long end = System.nanoTime();
System.out.println("第" + n + "个斐波那契数是" + f + ", 耗时" + TimeUnit.NANOSECONDS.toMillis(end - begin) + "毫秒");
}
}

第50个斐波那契数是12586269025, 耗时20461毫秒

    public static long calcWithoutRecursion(long n) {
if(n < 0)
return 0;
if(n == 0 || n == 1) {
return n;
}
long fib = 0;
long fibOne = 1;
long fibTwo = 1;
for(long i = 2; i < n; i++) {
fib = fibOne + fibTwo;
fibTwo = fibOne;
fibOne = fib;
}
return fib;
}

第50个斐波那契数是12586269025, 耗时0毫秒

02-06 442

12-01 252

01-23 8475

10-26 7345

09-08 4.5万

03-25 1025

03-07 630

06-09 36

01-23 3242

03-25 241