I wrote some simple code that generates the fibonacci sequence starting at just 32 bit variables in a for loop moving to 64 then, 128 bit. I cannot get past 182 generations with 128 bits. Is there a way I can rewrite this code to get past this limit?
This code can only generate 182 iterations
fn main() {
let mut in1: i128 = 1;
let mut in2: i128 = 1;
let mut op1: i128;
for iterations in 0..183 {
//add the given numbers
op1 = in1 + in2;
//print the result
println!("{}: {}", iterations + 1, op1);
//prepare the next iterations
in1 = in2;
in2 = op1;
//repeat
}
}
This code will give the following error if more than 182 generations are given
'main' panicked at 'attempt to add with overflow'"
There is no default data type beyond
i128. There are big integer libraries though, that allow for an arbitrary number of digits.For example,
num_bigint::BigInt, a sub-crate ofnum, and at the time of writing the most established big integer library (to my knowledge):Notice:
While
num_bigint::BigIntis the most established, it is by far not the fastest library.More info here: https://crates.io/crates/bigint-benchmark
However, please note that the fastest libraries are not MIT/Apache-2.0 licensed.