Comcast Interview Question

Implement fibonacci series

Interview Answer

Anonymous

Feb 22, 2017

Fibonacci is a series of numbers where the next number is the sum of the two previous numbers starting at 0: E.G. 0,1,1,2,3,5,8,13,21,34.... Generally the solution involves the last two numbers and a maximum number of iterations. E.G. the first 47 numbers in the series. Beyond 47 and you have to move to BigDecimal etc... import java.util.List; import java.util.ArrayList; class Main { public static void main(String[] args) { List hundredFibs = calcFibonnaciList(0,1,47); for(int fibs: hundredFibs) { System.out.println("Num: "+ fibs); } } public static List calcFibonnaciList(final int initial, final int second, final int numbersInSeries){ ArrayList fibsList = new ArrayList(100); // Initialize List fibsList.add(initial); fibsList.add(second); fillListwithFibSeries(initial,second,fibsList,numbersInSeries-2); return fibsList; } private static void fillListwithFibSeries(int prevPrev, int previous,List fibsList,int count) { if(count >0){ int nextNumber = prevPrev + previous; fibsList.add(nextNumber); fillListwithFibSeries(previous,nextNumber, fibsList,count-1); } } }