DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
codemouse92 profile image
Jason C. McDonald

I couldn't resist one more pass, using C.

int fib(n) {
    int p[2] = {0,1};
    int* r = &(p[n%2]);
    g: p[(n--)%2] = p[0]+p[1];
    if (n) {goto g;}
    return *r;
}

I'm using a pair to calculate the sequence, ergo the 2-element integer array.

Before I can do anything, though, I need to know where my answer will show up, so I create a pointer to the element which will eventually hold the result. That way, I can mutate n without fear. How this works will become apparent in a second.

This next line has a label, g, which I'll be using in a moment. In this math, I'm alternating which of the two elements in the pair are used to store the sum, and I'm switching between them by checking if n is even or odd (n%2), yielding either 1 (odd) or 0 (even). In the middle of that, I'm also decrementing n after I've used its value. I take the sum of the two elements, and save it in the target position in the pair. This way, I always have the latest two elements.

On the next line, if n has a non-zero value, I jump back to that previous line, using its g label. I'm using a goto statement, instead of an explicit loop or recursion (so, technically I hit one of the bonus goals? Debatable.)

Once I'm done, and n has reached zero, I return whatever was in the position I originally stored to look for the answer in. Remember how I was using the modulo to alternate spots? That same logic is at work here. If the original n was even, then the last value will get written to the first spot in the pair; if the original n is odd, then the second spot will be used.

Collapse
 
loki profile image
Loki Le DEV

Nice compact answer, goto still counts as a loop though ;)