I am trying to implement the Fibonacci sequence using callables and seeded the initial values of my Fibonacci callable with 3,4,5,6 and 2000. The output I get is as follows:
3 5 8 13
-820905900187520670
The problem is when I am trying to calculate fib(2000) in my callable. Can somebody take a look at my code provided below to see where I am going wrong with my approach:
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();}
}
}
Thanks
Java doesn’t throw an exception on overflow, just wraps the value around, that’s why you’re getting the strange result. Fibonacci is a fast growing sequence, the 2000. element is way beyond
longTry using
BigInteger, it will give you arbitrary precision (at the cost of performance obviously).