Created
January 11, 2015 03:31
-
-
Save 1995eaton/88a81ffb1b5c92641f40 to your computer and use it in GitHub Desktop.
Fibonacci Iterator function in Java 8
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.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