fibonacci.h

View source code here on GitHub!

Includes

type fibonacci

Implements the Iterator API and yields successive Fibonacci numbers.

uintmax_t (*iterator_function)(fibonacci *fib)

The function to advance the iterator and return the next element.

bool exhausted : 1

An indicator that tells you if the iterator is exhausted.

bool started : 1

An indicator that tells you if the interator has moved at all.

bool phase : 1

An indicator that flips every time the iterator moves.

uintmax_t a
uintmax_t b
uintmax_t limit

This represents the largest number the iterator is allowed to yield.

fibonacci fibonacci1(uintmax_t limit)
fibonacci fibonacci0()
 1#pragma once
 2
 3#include <stdint.h>
 4#include "iterator.h"
 5
 6typedef struct fibonacci fibonacci;
 7struct fibonacci    {
 8    IteratorHead(uintmax_t, fibonacci);
 9    uintmax_t a;
10    uintmax_t b;
11    uintmax_t limit;
12};
13
14uintmax_t advance_fibonacci(fibonacci *fib) {
15    if (fib->exhausted)
16        return 0;
17    IterationHead(fib);
18    uintmax_t tmp = fib->a + fib->b;
19    fib->a = fib->b;
20    fib->b = tmp;
21    fib->exhausted = (tmp > fib->limit);
22    return fib->a;
23}
24
25fibonacci fibonacci1(uintmax_t limit) {
26    fibonacci ret;
27    IteratorInitHead(ret, advance_fibonacci);
28    ret.a = 0;
29    ret.b = 1;
30    ret.limit = limit;
31    return ret;
32}
33
34fibonacci fibonacci0();
35inline fibonacci fibonacci0() {
36    return fibonacci1(-1);
37}

Tags: c-iterator, fibonacci-number