2

我正在尝试使用可调用对象来实现斐波那契数列,并使用 3、4、5、6 和 2000 播种我的斐波那契可调用对象的初始值。我得到的输出如下:

3 5 8 13 -820905900187520670

问题是当我试图在我的可调用对象中计算 fib(2000) 时。有人可以看看我下面提供的代码,看看我的方法哪里出错了:

import java.util.concurrent.*;
import java.util.*;

class FibonacciGen implements Callable<Long>{
    private Long fib;
    public FibonacciGen(long num){
        this.fib = num;
    }
    public Long call(){
        return calculateFibonacci(fib);
    }

    private long calculateFibonacci(long someNum){
        long firstNum = 0L;
        long secondNum = 1L;
        long counter = 0L;
        while(counter<someNum){
            long fibCalc = secondNum+firstNum;
            firstNum = secondNum;
            secondNum = fibCalc;
            counter= counter+1L;
        }
        return secondNum;
    }   

}

public class FibonacciCallable{
    public static void main(String[] args){
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Callable<Long>> results = new ArrayList<Callable<Long>>();
        CompletionService<Long> ecs = new ExecutorCompletionService<Long>(exec);
        results.add(new FibonacciGen(3L));
        results.add(new FibonacciGen(4L));
        results.add(new FibonacciGen(5L));
        results.add(new FibonacciGen(6L));
        results.add(new FibonacciGen(2000L));
            try{
                for(Callable<Long> fs:results){
                    ecs.submit(fs);
                }
                System.out.println("Submitted all the tasks");
                int n = results.size();
                for(int i=0;i<n;++i){
                    System.out.println("Taking the first completed task");
                    Long r = ecs.take().get();
                    if(r != null)
                        System.out.println(r);
                    }   


            }
            catch(InterruptedException ex){System.out.println(ex);return;}
            catch(ExecutionException e){System.out.println(e);}
            finally{exec.shutdown();}
        }
}

谢谢

4

1 回答 1

6

Java 不会在溢出时抛出异常,只是将值包装起来,这就是为什么你会得到奇怪的结果。斐波那契是一个快速增长的序列,2000 年。元素远远超出long

尝试使用BigInteger,它将为您提供任意精度(显然以性能为代价)。

于 2012-04-19T17:19:07.250 回答