Created
June 22, 2018 02:22
-
-
Save mkdika/5e1e3528ac758cc3043f1c6a6e89d3fa to your computer and use it in GitHub Desktop.
Fibonacci value n position with Java 8 Stream API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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