Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created January 12, 2015 00:36
Show Gist options
  • Save 1995eaton/6edcda43faed3bbe1235 to your computer and use it in GitHub Desktop.
Save 1995eaton/6edcda43faed3bbe1235 to your computer and use it in GitHub Desktop.
Fib class in Java
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