Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created January 11, 2015 03:31
Show Gist options
  • Save 1995eaton/88a81ffb1b5c92641f40 to your computer and use it in GitHub Desktop.
Save 1995eaton/88a81ffb1b5c92641f40 to your computer and use it in GitHub Desktop.
Fibonacci Iterator function in Java 8
import java.util.Iterator;
import java.math.BigInteger;
class Main {
public static Iterable<BigInteger> fibonacci(final long N) {
return () -> new Iterator<BigInteger>() {
private long cursor = 0;
private BigInteger a = BigInteger.ZERO,
b = BigInteger.ONE;
public boolean hasNext() {
return cursor < N;
}
public BigInteger next() {
++cursor;
final BigInteger temp = a;
a = b;
b = b.add(temp);
return a;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(final String[] args) {
for (BigInteger e: fibonacci(100000)) {
System.out.println(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment