Created
January 12, 2015 00:36
-
-
Save 1995eaton/6edcda43faed3bbe1235 to your computer and use it in GitHub Desktop.
Fib class in Java
This file contains 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
import java.util.List; | |
import java.util.stream.Stream; | |
import java.util.stream.Collectors; | |
import java.util.function.Supplier; | |
import java.math.BigInteger; | |
class Fibonacci { | |
private static Stream<BigInteger> getGenerator() { | |
return Stream.generate(new Supplier<BigInteger>() { | |
private BigInteger a = BigInteger.ZERO; | |
private BigInteger b = BigInteger.ONE; | |
@Override public BigInteger get() { | |
BigInteger t = a; | |
a = b; | |
b = b.add(t); | |
return a; | |
} | |
}); | |
} | |
public static Stream<BigInteger> generate() { | |
return getGenerator(); | |
} | |
public static List<BigInteger> generate(int n) { | |
return getGenerator().limit(n).collect(Collectors.toList()); | |
} | |
public static BigInteger nth(int n) { | |
return getGenerator().limit(n).reduce((a, b) -> b).get(); | |
} | |
} | |
class Main { | |
public static void main(String[] args) { | |
System.out.println(Fibonacci.generate(50)); | |
Fibonacci.generate().limit(50).forEach(System.out::println); | |
System.out.println(Fibonacci.nth(50)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment