使用Callables实现Fibonacci时无声长溢出

时间:2012-04-19 17:11:13

标签: java long-integer fibonacci integer-overflow callable

我正在尝试使用callables实现Fibonacci序列,并将我的Fibonacci的初始值调用为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();}
        }
}

由于

1 个答案:

答案 0 :(得分:6)

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

尝试使用BigInteger,它会给你任意精确度(显然是以性能为代价)。