Skip to content

Instantly share code, notes, and snippets.

@lisael
Created May 10, 2022 21:31
Show Gist options
  • Save lisael/434573a16733b114d09e221e92b3ed1a to your computer and use it in GitHub Desktop.
Save lisael/434573a16733b114d09e221e92b3ed1a to your computer and use it in GitHub Desktop.
fibonacciIter is not even optimized...
const std = @import("std");
const time = std.time;
pub fn main() anyerror!void {
const fibo_arg = 30;
var start = time.nanoTimestamp();
var end = time.nanoTimestamp();
std.debug.print("noop - {}ns\n", .{end - start});
start = time.nanoTimestamp();
var result = fibonacciRecurse(fibo_arg);
end = time.nanoTimestamp();
std.debug.print("fibonacciRecurse({}) -> {} - {}ns\n", .{ fibo_arg, result, end - start });
start = time.nanoTimestamp();
result = fibonacciIter(fibo_arg);
end = time.nanoTimestamp();
std.debug.print("fibonacciIter({}) -> {} - {}ns\n", .{ fibo_arg, result, end - start });
}
fn fibonacciRecurse(n: u64) u64 {
return if (n < 2) 1 else fibonacciRecurse(n - 1) + fibonacciRecurse(n - 2);
}
fn fibonacciIter(n: u64) u64 {
if (n < 2) return n;
var result: u64 = 1;
var prev: u64 = 1;
var it: u64 = 2;
while (it <= n) {
const before = result;
result += prev;
prev = before;
it += 1;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment