gpt4 book ai didi

java - 使用 Callables 实现 Fibonacci 时静默长溢出

转载 作者:行者123 更新时间:2023-11-30 05:53:47 24 4
gpt4 key购买 nike

我正在尝试使用可调用项来实现斐波那契数列,并使用 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();}
}
}

谢谢

最佳答案

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

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

关于java - 使用 Callables 实现 Fibonacci 时静默长溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com