public class FibonacciWhile extends Fibonacci {
public ArrayList FibonacciWhile(int nth) {
ArrayList fib = new ArrayList<>();
int i=0;
while (i<nth) {
if (i == 0) {
fib.add(1);
} else if (i == 1) {
fib.add(1);
} else {
fib.add(fib.get(i - 2) + fib.get(i - 1));
}
i++;
}
return fib;
}
}
public class FibonacciFor extends Fibonacci {
public ArrayList FibonacciFor(int nth) {
ArrayList fib = new ArrayList<>();
for (int i = 0; i < nth; i++) {
if (i == 0) {
fib.add(1);
} else if (i == 1) {
fib.add(1);
} else {
fib.add(fib.get(i - 2) + fib.get(i - 1));
}
}
return fib;
}
}
public class FibonacciRecursive extends Fibonacci {
ArrayList fib = new ArrayList<>();
public ArrayList FibonacciRecursive(int i, int nth) {
if (i<nth) {
if (i == 0) {
fib.add(1);
} else if (i == 1) {
fib.add(1);
} else {
fib.add(fib.get(i - 2) + fib.get(i - 1));
}
FibonacciRecursive(i+1, nth);
}
return fib;
}
}
public class FibonacciStream extends Fibonacci {
public ArrayList FibonacciStream(int nth) {
return Stream.iterate(new int[]{1, 1}, fib -> new int[]{fib[1], fib[0] + fib[1]})
.limit(nth)
.map(fib -> fib[0])
.collect(Collectors.toCollection(ArrayList::new));
}
}