multithreading - Java ExecutorService to solve Recursive Fibonacci Series -
i need find out number based on index in fibonacci series recursively using threads , tried following code, program never ends. please let me know if missing something.
code:
import java.math.biginteger; import java.util.concurrent.*; public class multithreadedfib { private executorservice executorservice; public multithreadedfib(final int numberofthreads) { executorservice = executors.newfixedthreadpool(numberofthreads); } public biginteger getfibnumberatindex(final int index) throws interruptedexception, executionexception { future<biginteger> indexminusone = executorservice.submit( new callable<biginteger>() { public biginteger call() throws interruptedexception, executionexception { return getnumber(index - 1); } }); future<biginteger> indexminustwo = executorservice.submit( new callable<biginteger>() { public biginteger call() throws interruptedexception, executionexception { return getnumber(index - 2); } }); return indexminusone.get().add(indexminustwo.get()); } public biginteger getnumber(final int index) throws interruptedexception, executionexception { if (index == 0 || index == 1) return biginteger.valueof(index); return getfibnumberatindex(index - 1).add(getfibnumberatindex(index - 2)); } } fixed it (thanks fiver)
instead of calling getnumber(int) call method, calling dynamic programming algorithm computes number @ index.
the code is:
public class dynamicfib implements ifib { private map<integer, biginteger> memoize = new hashmap<integer, biginteger>(); public dynamicfib() { memoize.put(0, biginteger.zero); memoize.put(1, biginteger.one); } public biginteger getfibnumberatindex(final int index) { if (!memoize.containskey(index)) memoize.put(index, getfibnumberatindex(index - 1).add(getfibnumberatindex(index - 2))); return memoize.get(index); } }
this recursion overflow stack fast. because computing lower fibonacci numbers on , on again - exponentially many number of times.
one effective way avoid use memoized recursion (a dynamic programming approach)
basically use static array hold computed fibonacci numbers , whenever need one, take array, if it's computed. if not, compute , store in array. way each number computed once.
(you can use other data structure instead of array, of course, i.e. hashtable)
Comments
Post a Comment