Skip to content

Instantly share code, notes, and snippets.

@mkdika
Created June 22, 2018 02:22
Show Gist options
  • Save mkdika/5e1e3528ac758cc3043f1c6a6e89d3fa to your computer and use it in GitHub Desktop.
Save mkdika/5e1e3528ac758cc3043f1c6a6e89d3fa to your computer and use it in GitHub Desktop.
Fibonacci value n position with Java 8 Stream API
package algorithms.streams;
import java.math.BigInteger;
import java.util.stream.Stream;
/**
*
* @author Maikel Chandika ([email protected])
*
* to calculate Fibonacci n position with Java 8 Stream API.
* Support large number of n calculation (Using BigInteger).
*
*/
public class FibonacciStream {
public static void main(String[] args) {
System.out.println(calFibs(50)); // 12586269025
System.out.println(calFibs(1000)); // too long ;)
}
static java.math.BigInteger calFibs(int n) {
return Stream.iterate(new BigInteger[]{BigInteger.ZERO, BigInteger.ONE}, s -> new BigInteger[]{s[1], s[0].add(s[1])})
.limit(n)
.reduce((x, y) -> y).orElse(null)[1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment