I have the following tail recursive fibonacci function in zig, rust, julia and c. For some reason, only the Julia version doesn’t overflow. Why is that?
fn fib(n: usize, p1: usize, p2: usize) -> usize {
if n < 2 {
return p1 + p2;
}
return fib(n - 1, p1 + p2, p1);
}
fn main() {
dbg!(fib(100, 1, 1));
}
const std = @import("std");
fn fib(n: usize, p1: usize, p2: usize) usize {
if (n < 2) {
return p1 + p2;
}
return fib(n - 1, p1 + p2, p1);
}
pub fn main() !void {
std.debug.print("fib(100, 1, 1) = {d}", .{fib(100, 1, 1)});
}
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
uint64_t fib(uint64_t n, uint64_t p1, uint64_t p2) {
if (n < 2)
return p1 + p2;
return fib(n - 1, p1 + p2, p1);
}
int main() {
printf("fib(100, 1, 1) = %" PRIu64 "\n", fib(100, 1, 1));
return 0;
}
function fib(n::UInt64, p1::UInt64, p2::UInt64) ::UInt64
if (n < 2)
return p1 + p2
end
return fib(n - 1, p1 + p2, p1)
end
@show fib(UInt64(100), UInt64(1), UInt64(1))
And running all of them:
$ rustc -o fibrs fib.rs && ./fibrs
thread 'main' (10899) panicked at fib.rs:5:23:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
$ zig build-exe --name fibz fib.zig && ./fibz
thread 10921 panic: integer overflow
...
$ gcc -o fibc fib.c && ./fibc
fib(100, 1, 1) = 101
$ julia fib.jl
fib(UInt64(100), UInt64(1), UInt64(1)) = 0x45e1a61e5624f888
Why does Julia not overflow? Am I missing something? I think my implementations are all the same. The actual code I’ve uploaded to my GitHub
Edit: I’m a dummy and my C code was buggy. Both julia and C overflow