Created
June 23, 2015 18:23
-
-
Save apense/264fde24ef3b587aace2 to your computer and use it in GitHub Desktop.
Fibonacci numbers and Factorials as iterators
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
iterator factorials(k: int): int = | |
## Yields from 0! to k! as an iterator | |
var (n, f) = (0, 1) | |
yield 1 # for 0! | |
while n < k: | |
yield f | |
n = n + 1; f = f * (n + 1) | |
iterator fibonacci(cap: int): int = | |
## Yields Fibonacci numbers <= `cap` as an iterator | |
var (a, b) = (0, 1) | |
while a <= cap: | |
yield a | |
let tmp = a | |
a = b | |
b = tmp + b | |
for f in factorials(10): | |
echo f | |
for f in fibonacci(1000): | |
echo f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment