aboutsummaryrefslogtreecommitdiff
path: root/examples/snippets/fibonacci.zig
blob: 327bbd3fb847e00a1c3bb6110da9d76bf7509811 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const std = @import("std");

/// Compute the nth Fibonacci number iteratively.
pub fn fibonacci(n: u64) u64 {
    if (n <= 1) return n;
    var a: u64 = 0;
    var b: u64 = 1;
    var i: u64 = 2;
    while (i <= n) : (i += 1) {
        const next = a + b;
        a = b;
        b = next;
    }
    return b;
}

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    var buf: [4096]u8 = undefined;
    var fw: std.Io.File.Writer = .init(.stdout(), io, &buf);
    defer fw.interface.flush() catch {};
    const w = &fw.interface;

    try w.print("Fibonacci sequence (first 12 terms):\n", .{});
    for (0..12) |n| {
        try w.print("  fib({d}) = {d}\n", .{ n, fibonacci(n) });
    }
}

test "fibonacci base cases" {
    try std.testing.expectEqual(@as(u64, 0), fibonacci(0));
    try std.testing.expectEqual(@as(u64, 1), fibonacci(1));
    try std.testing.expectEqual(@as(u64, 1), fibonacci(2));
}

test "fibonacci sequence" {
    const expected = [_]u64{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
    for (expected, 0..) |v, n| {
        try std.testing.expectEqual(v, fibonacci(n));
    }
}