Programming Search⌘K

Taskintro

Compute Fibonacci numbers

Also called fibonacci, fib, Fibonacci sequence, nth Fibonacci number, memoized fibonacci, functools.cache, Binet's formula.

Compute the nth Fibonacci number with a loop that keeps the last two numbers. F(92) is the largest in 64 bits. Naive recursion is slow, and a float formula is not exact.

Task

Compute the nth Fibonacci number. The sequence starts with 0 and 1, and each next number is the sum of the two numbers before it. So F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n greater than 1. The Rosetta Code task says: "Write a function to generate the nth Fibonacci number"1.

Some texts start the sequence at F(1) = 1 and F(2) = 1, "though many authors also include a zeroth element F0 = 0"2. This page starts at F(0) = 0. The sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

The function fibonacci(n) returns F(n). For example, fibonacci(10) is 55.

The loop keeps only the last two numbers:

  1. If n is 0, the answer is 0.
  2. Set a to 0 and b to 1.
  3. Repeat n - 1 times: replace the pair (a, b) with (b, a + b).
  4. The answer is b.

The loop takes n - 1 additions and a fixed amount of memory. The numbers grow fast: F(47) does not fit in 32 bits, and F(93) does not fit in 64 bits. So the contract has the range 0 to 92. For larger n, use big integers.

Solutions

Language 64-bit loop Big result
Python a loop; Python integers have no size limit the same
JavaScript, TypeScript a loop with BigInt values the same
Java a loop with Math.addExact BigInteger.add in a loop
C# a loop with checked BigInteger in a loop
Go a loop big.Int.Add in a loop
Rust a loop with checked_add none in the standard library
C a loop with long long none
C++ a constexpr loop with long long none
Bash a loop with $((a + b)) bc
  • Python. There is no Fibonacci function. The loop uses tuple assignment, a, b = b, a + b, and Python integers have no size limit.
  • JavaScript. There is no Fibonacci function. A number holds integers exactly only up to 2 to the power 53, so the solution uses BigInt. "BigInt values represent integer values which are too high or too low to be represented by the number primitive"3.
  • TypeScript. The same code as JavaScript, with the type bigint.
  • Java. Math.addExact "Returns the sum of its arguments, throwing an exception if the result overflows a long"4. For larger numbers, use BigInteger.
  • C#. A checked block throws OverflowException on overflow. For larger numbers, use BigInteger.
  • Go. A loop with int64 values. Go integers wrap around on overflow with no error, so the contract range is important. For larger numbers, use big.Int.
  • Rust. checked_add is "Checked integer addition. Computes self + rhs, returning None if overflow occurred"5. The solution returns None when the result does not fit.
  • C. The solution uses a loop with long long values.
  • C++. The same loop as C, as a constexpr function.
  • Bash. The solution uses a loop with $((a + b)).

The Python loop, with the first 13 numbers and a big result:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a


print([fibonacci(n) for n in range(13)])
print(fibonacci(100))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
354224848179261915075

The recursive form follows the definition. The Rosetta Code task says that "recursive solutions are generally considered too slow and are mostly used as an exercise in recursion"1, because each call makes two more calls. A cache stores each result, so each number is computed once. In Python, functools.cache is a "Simple lightweight unbounded function cache"6:

import functools


@functools.cache
def fibonacci(n):
    return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)


print(fibonacci(90))
print(fibonacci.cache_info())
Output
2880067194370816120
CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)

The cached form still uses one stack frame for each step, so the loop is better.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • ten, twenty and thirty: small numbers.
  • zero: F(0) is 0. A loop that always returns b gives 1.
  • one and two: F(1) and F(2) are both 1.
  • largest-32-bit: F(46) is 1836311903, the largest Fibonacci number in a 32-bit signed integer.
  • beyond-32-bit: F(47) is 2971215073, which needs more than 32 bits.
  • binet-fails: F(71) is 308061521170129. The float formula gives 308061521170130.
  • largest-64-bit: F(92) is 7540113804746346429, the largest Fibonacci number in a 64-bit signed integer.

Pitfalls

  • Naive recursion is slow. The recursive form without a cache computes the same numbers again and again. The count of calls grows as fast as the numbers. For F(30), it makes more than 2.6 million calls:
calls = 0


def fibonacci(n):
    global calls
    calls += 1
    return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)


print(fibonacci(30), calls)
Output
832040 2692537

Each recursive form also has a depth limit. In Python, sys.getrecursionlimit() returns "the maximum depth of the Python interpreter stack"7, so a cached fibonacci(5000) fails with RecursionError if no smaller value is in the cache.

  • The sum overflows with no error. F(93) does not fit in 64 bits. In Go, the sum wraps around and gives a negative number:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func fibonacci(n int) int64 {
	a, b := int64(0), int64(1)
	for i := 0; i < n; i++ {
		a, b = b, a+b
	}
	return a
}

func main() {
	fmt.Println(fibonacci(92))
	fmt.Println(fibonacci(93))
}
Output
7540113804746346429
-6246583658587674878

See Integer overflow or wraparound and Use big integers.

  • The loop computes one number too many. The short loop runs n times and returns a, so its last step computes F(n + 1) in b. For F(92), that step overflows, although F(92) fits. With a checked addition, the short loop fails for a valid input. Run the loop n - 1 times and return b:

This code runs but gives a wrong answer on purpose.

fn short_loop(n: u32) -> Option<i64> {
    let (mut a, mut b) = (0i64, 1i64);
    for _ in 0..n {
        let next = a.checked_add(b)?;
        a = b;
        b = next;
    }
    Some(a)
}

fn fixed_loop(n: u32) -> Option<i64> {
    if n == 0 {
        return Some(0);
    }
    let (mut a, mut b) = (0i64, 1i64);
    for _ in 1..n {
        let next = a.checked_add(b)?;
        a = b;
        b = next;
    }
    Some(b)
}

fn main() {
    println!("{:?} {:?}", short_loop(92), fixed_loop(92));
}
Output
None Some(7540113804746346429)
  • The float formula is not exact. Binet's formula gives F(n) from the golden ratio. "It has become known as Binet's formula"2, and F(n) is the nearest integer to the golden ratio to the power n, divided by the square root of 5. The formula is exact in real numbers, but a 64-bit float has 53 bits of precision. From F(71), the rounded result is wrong:

This code runs but gives a wrong answer on purpose.

const phi = (1 + Math.sqrt(5)) / 2;
const binet = (n) => Math.round(phi ** n / Math.sqrt(5));
let a = 0n;
let b = 1n;
for (let i = 0; i < 71; i++) {
  [a, b] = [b, a + b];
}
console.log(binet(70), binet(71));
console.log(a);
Output
190392490709135 308061521170130
308061521170129n

For a large n, the fast doubling method computes F(n) in about log2(n) steps. The algorithm is on the algorithm site: Fibonacci by fast doubling.

Code

The build runs the native tests of each language in a pinned toolchain.

fibonacci.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import functools


def fibonacci(n: int) -> int:
    """Return F(n) with a loop that keeps the last two numbers."""
    if n < 0:
        raise ValueError("n is negative")
    if n == 0:
        return 0
    a, b = 0, 1
    for _ in range(n - 1):
        a, b = b, a + b
    return b


@functools.cache
def fibonacci_cached(n: int) -> int:
    """Return F(n) with recursion and a cache. Each step uses one stack frame."""
    return n if n < 2 else fibonacci_cached(n - 1) + fibonacci_cached(n - 2)
test_fibonacci.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import pytest

from fibonacci import fibonacci, fibonacci_cached

CASES = [
    ("ten", 10, 55),
    ("twenty", 20, 6765),
    ("thirty", 30, 832040),
    ("zero", 0, 0),
    ("one", 1, 1),
    ("two", 2, 1),
    ("largest-32-bit", 46, 1836311903),
    ("beyond-32-bit", 47, 2971215073),
    ("binet-fails", 71, 308061521170129),
    ("largest-64-bit", 92, 7540113804746346429),
]


@pytest.mark.parametrize(("name", "n", "want"), CASES, ids=[c[0] for c in CASES])
def test_fibonacci(name, n, want):
    assert fibonacci(n) == want
    assert fibonacci_cached(n) == want


def test_big():
    assert fibonacci(100) == 354224848179261915075


def test_negative_raises():
    with pytest.raises(ValueError):
        fibonacci(-1)
fibonacci.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

#ifndef FIBONACCI_HPP
#define FIBONACCI_HPP

// Returns F(n) for 0 <= n <= 92. constexpr lets the compiler compute the
// Fibonacci number of a constant.
constexpr long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    }
    long long a = 0;
    long long b = 1;
    for (int i = 1; i < n; i++) {
        const long long next = a + b;
        a = b;
        b = next;
    }
    return b;
}

#endif
test_fibonacci.cpp 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

#include <cstdio>

#include "fibonacci.hpp"

namespace {

struct test_case {
    const char* name;
    int n;
    long long want;
};

const test_case cases[] = {
    {"ten", 10, 55},
    {"twenty", 20, 6765},
    {"thirty", 30, 832040},
    {"zero", 0, 0},
    {"one", 1, 1},
    {"two", 2, 1},
    {"largest-32-bit", 46, 1836311903},
    {"beyond-32-bit", 47, 2971215073LL},
    {"binet-fails", 71, 308061521170129LL},
    {"largest-64-bit", 92, 7540113804746346429LL},
};

static_assert(fibonacci(10) == 55);

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const long long got = fibonacci(c.n);
        if (got != c.want) {
            std::printf("FAIL %s: %lld\n", c.name, got);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Fibonacci.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import java.math.BigInteger;

/** Fibonacci numbers, with F(0) = 0 and F(1) = 1. */
public final class Fibonacci {
    private Fibonacci() {}

    /** Returns F(n). addExact throws ArithmeticException above F(92). */
    public static long fibonacci(long n) {
        if (n < 0) {
            throw new IllegalArgumentException("n is negative");
        }
        if (n == 0) {
            return 0;
        }
        long a = 0;
        long b = 1;
        for (long i = 1; i < n; i++) {
            long next = Math.addExact(a, b);
            a = b;
            b = next;
        }
        return b;
    }

    /** Returns F(n) as a BigInteger, with no size limit. */
    public static BigInteger bigFibonacci(int n) {
        BigInteger a = BigInteger.ZERO;
        BigInteger b = BigInteger.ONE;
        for (int i = 0; i < n; i++) {
            BigInteger next = a.add(b);
            a = b;
            b = next;
        }
        return a;
    }
}
FibonacciTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class FibonacciTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("ten", 10L, 55L),
                Arguments.of("twenty", 20L, 6765L),
                Arguments.of("thirty", 30L, 832040L),
                Arguments.of("zero", 0L, 0L),
                Arguments.of("one", 1L, 1L),
                Arguments.of("two", 2L, 1L),
                Arguments.of("largest-32-bit", 46L, 1836311903L),
                Arguments.of("beyond-32-bit", 47L, 2971215073L),
                Arguments.of("binet-fails", 71L, 308061521170129L),
                Arguments.of("largest-64-bit", 92L, 7540113804746346429L)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void fibonacci(String name, long n, long want) {
        assertEquals(want, Fibonacci.fibonacci(n));
        assertEquals(BigInteger.valueOf(want), Fibonacci.bigFibonacci((int) n));
    }

    @Test
    void overflowThrows() {
        assertThrows(ArithmeticException.class, () -> Fibonacci.fibonacci(93));
        assertEquals(new BigInteger("12200160415121876738"), Fibonacci.bigFibonacci(93));
    }
}
fibonacci.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

#include "fibonacci.h"

long long fibonacci(int n) {
    if (n == 0) {
        return 0;
    }
    long long a = 0;
    long long b = 1;
    for (int i = 1; i < n; i++) {
        long long next = a + b;
        a = b;
        b = next;
    }
    return b;
}
fibonacci.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

#ifndef FIBONACCI_H
#define FIBONACCI_H

// Returns F(n) for 0 <= n <= 92. Above 92, the sum overflows, which is
// undefined behavior for a signed type.
long long fibonacci(int n);

#endif
test_fibonacci.c 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

#include "fibonacci.h"

#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    int n;
    long long want;
};

static const struct test_case cases[] = {
    {"ten", 10, 55},
    {"twenty", 20, 6765},
    {"thirty", 30, 832040},
    {"zero", 0, 0},
    {"one", 1, 1},
    {"two", 2, 1},
    {"largest-32-bit", 46, 1836311903},
    {"beyond-32-bit", 47, 2971215073LL},
    {"binet-fails", 71, 308061521170129LL},
    {"largest-64-bit", 92, 7540113804746346429LL},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        long long got = fibonacci(c->n);
        if (got != c->want) {
            printf("FAIL %s: %lld\n", c->name, got);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Fibonacci.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

using System;

/// <summary>Fibonacci numbers, with F(0) = 0 and F(1) = 1.</summary>
public static class Fibonacci
{
    /// <summary>Returns F(n). The checked addition throws OverflowException above F(92).</summary>
    public static long Compute(long n)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(n);
        if (n == 0)
        {
            return 0;
        }
        long a = 0;
        long b = 1;
        for (long i = 1; i < n; i++)
        {
            (a, b) = (b, checked(a + b));
        }
        return b;
    }
}
FibonacciTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

using System;
using Xunit;

public sealed class FibonacciTests
{
    public static TheoryData<string, long, long> Cases => new()
    {
        { "ten", 10, 55 },
        { "twenty", 20, 6765 },
        { "thirty", 30, 832040 },
        { "zero", 0, 0 },
        { "one", 1, 1 },
        { "two", 2, 1 },
        { "largest-32-bit", 46, 1836311903 },
        { "beyond-32-bit", 47, 2971215073 },
        { "binet-fails", 71, 308061521170129 },
        { "largest-64-bit", 92, 7540113804746346429 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Compute(string name, long n, long want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Fibonacci.Compute(n));
    }

    [Fact]
    public void OverflowThrows()
    {
        Assert.Throws<OverflowException>(() => Fibonacci.Compute(93));
        Assert.Throws<ArgumentOutOfRangeException>(() => Fibonacci.Compute(-1));
    }
}
fibonacci.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

/** Returns F(n) as a BigInt for a non-negative BigInt n. */
export function fibonacci(n) {
  if (n < 0n) {
    throw new RangeError("n is negative");
  }
  if (n === 0n) {
    return 0n;
  }
  let a = 0n;
  let b = 1n;
  for (let i = 1n; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return b;
}
fibonacci.test.js 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fibonacci } from "./fibonacci.js";

const cases = [
  ["ten", 10n, 55n],
  ["twenty", 20n, 6765n],
  ["thirty", 30n, 832040n],
  ["zero", 0n, 0n],
  ["one", 1n, 1n],
  ["two", 2n, 1n],
  ["largest-32-bit", 46n, 1836311903n],
  ["beyond-32-bit", 47n, 2971215073n],
  ["binet-fails", 71n, 308061521170129n],
  ["largest-64-bit", 92n, 7540113804746346429n],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(fibonacci(n), want);
  });
}

test("big", () => {
  assert.equal(fibonacci(100n), 354224848179261915075n);
});

test("negative", () => {
  assert.throws(() => fibonacci(-1n), RangeError);
});
fibonacci.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

/** Returns F(n) as a BigInt for a non-negative BigInt n. */
export function fibonacci(n: bigint): bigint {
  if (n < 0n) {
    throw new RangeError("n is negative");
  }
  if (n === 0n) {
    return 0n;
  }
  let a = 0n;
  let b = 1n;
  for (let i = 1n; i < n; i++) {
    [a, b] = [b, a + b];
  }
  return b;
}
fibonacci.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { fibonacci } from "./fibonacci.ts";

const cases: [string, bigint, bigint][] = [
  ["ten", 10n, 55n],
  ["twenty", 20n, 6765n],
  ["thirty", 30n, 832040n],
  ["zero", 0n, 0n],
  ["one", 1n, 1n],
  ["two", 2n, 1n],
  ["largest-32-bit", 46n, 1836311903n],
  ["beyond-32-bit", 47n, 2971215073n],
  ["binet-fails", 71n, 308061521170129n],
  ["largest-64-bit", 92n, 7540113804746346429n],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(fibonacci(n), want);
  });
}

test("big", () => {
  assert.equal(fibonacci(100n), 354224848179261915075n);
});

test("negative", () => {
  assert.throws(() => fibonacci(-1n), RangeError);
});
fibonacci.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

// Package fibonacci computes Fibonacci numbers, with F(0) = 0 and F(1) = 1.
package fibonacci

import "math/big"

// Fibonacci returns F(n) for 0 <= n <= 92. Above 92, the sum wraps around.
func Fibonacci(n int64) int64 {
	if n == 0 {
		return 0
	}
	a, b := int64(0), int64(1)
	for i := int64(1); i < n; i++ {
		a, b = b, a+b
	}
	return b
}

// Big returns F(n) as a big.Int, with no size limit.
func Big(n int64) *big.Int {
	a, b := big.NewInt(0), big.NewInt(1)
	for i := int64(0); i < n; i++ {
		a.Add(a, b)
		a, b = b, a
	}
	return a
}
fibonacci_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

package fibonacci

import "testing"

var cases = []struct {
	name string
	n    int64
	want int64
}{
	{"ten", 10, 55},
	{"twenty", 20, 6765},
	{"thirty", 30, 832040},
	{"zero", 0, 0},
	{"one", 1, 1},
	{"two", 2, 1},
	{"largest-32-bit", 46, 1836311903},
	{"beyond-32-bit", 47, 2971215073},
	{"binet-fails", 71, 308061521170129},
	{"largest-64-bit", 92, 7540113804746346429},
}

func TestFibonacci(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Fibonacci(c.n); got != c.want {
				t.Fatalf("Fibonacci(%d) = %d, want %d", c.n, got, c.want)
			}
			if got := Big(c.n); !got.IsInt64() || got.Int64() != c.want {
				t.Fatalf("Big(%d) = %v", c.n, got)
			}
		})
	}
}

func TestBig(t *testing.T) {
	if got := Big(100).String(); got != "354224848179261915075" {
		t.Fatalf("Big(100) = %s", got)
	}
}
fibonacci.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

/// Returns F(n), or None if F(n) does not fit in an i64.
pub fn checked_fibonacci(n: u32) -> Option<i64> {
    if n == 0 {
        return Some(0);
    }
    let (mut a, mut b) = (0i64, 1i64);
    for _ in 1..n {
        let next = a.checked_add(b)?;
        a = b;
        b = next;
    }
    Some(b)
}

/// Returns F(n) for 0 <= n <= 92.
pub fn fibonacci(n: i64) -> i64 {
    let n = u32::try_from(n).expect("n is negative or too large");
    checked_fibonacci(n).expect("F(n) does not fit in an i64")
}
tests/fibonacci_test.rs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

use algo_compute_fibonacci_numbers::{checked_fibonacci, fibonacci};

const CASES: &[(&str, i64, i64)] = &[
    ("ten", 10, 55),
    ("twenty", 20, 6765),
    ("thirty", 30, 832040),
    ("zero", 0, 0),
    ("one", 1, 1),
    ("two", 2, 1),
    ("largest-32-bit", 46, 1836311903),
    ("beyond-32-bit", 47, 2971215073),
    ("binet-fails", 71, 308061521170129),
    ("largest-64-bit", 92, 7540113804746346429),
];

#[test]
fn cases() {
    for &(name, n, want) in CASES {
        assert_eq!(fibonacci(n), want, "{name}");
    }
}

#[test]
fn overflow_is_none() {
    assert_eq!(checked_fibonacci(92), Some(7540113804746346429));
    assert_eq!(checked_fibonacci(93), None);
}
fibonacci.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

# fibonacci N
# Prints F(N) for 0 <= N <= 92. Bash arithmetic does not check for overflow.
# Returns 1 if N is negative.
fibonacci() {
  local n=$1 a=0 b=1 next i
  if ((n < 0)); then
    return 1
  fi
  if ((n == 0)); then
    printf '0\n'
    return 0
  fi
  for ((i = 1; i < n; i++)); do
    next=$((a + b))
    a=$b
    b=$next
  done
  printf '%s\n' "$b"
}
test_fibonacci.bats 20 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-fibonacci-numbers/.

setup() {
  source "$BATS_TEST_DIRNAME/fibonacci.sh"
}

@test "ten" { run fibonacci 10; [ "$output" = "55" ]; }
@test "twenty" { run fibonacci 20; [ "$output" = "6765" ]; }
@test "thirty" { run fibonacci 30; [ "$output" = "832040" ]; }
@test "zero" { run fibonacci 0; [ "$output" = "0" ]; }
@test "one" { run fibonacci 1; [ "$output" = "1" ]; }
@test "two" { run fibonacci 2; [ "$output" = "1" ]; }
@test "largest-32-bit" { run fibonacci 46; [ "$output" = "1836311903" ]; }
@test "beyond-32-bit" { run fibonacci 47; [ "$output" = "2971215073" ]; }
@test "binet-fails" { run fibonacci 71; [ "$output" = "308061521170129" ]; }
@test "largest-64-bit" { run fibonacci 92; [ "$output" = "7540113804746346429" ]; }

@test "negative-fails" { run fibonacci -1; [ "$status" -eq 1 ]; }

References

  1. Rosetta Code, Fibonacci sequence (task text, from acmeism/RosettaCodeData), task text
  2. Wikipedia, Fibonacci sequence, Definition; Closed-form expression; Computation by rounding
  3. MDN Web Docs, BigInt, the introduction
  4. Java SE 25 API, Class Math, addExact(long, long)
  5. Rust standard library, primitive type i64, checked_add
  6. The Python Standard Library, functools, cache
  7. The Python Standard Library, sys, getrecursionlimit

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source