Search code examples
rustdata-management

How can I allow Rust to preform operations on numbers past 128bits?


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'"


Solution

  • 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 of num, and at the time of writing the most established big integer library (to my knowledge):

    use num_bigint::BigInt;
    
    fn main() {
        let mut in1: BigInt = 1.into();
        let mut in2: BigInt = 1.into();
        let mut op1: BigInt;
    
        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
        }
    }
    
    ...
    179: 30010821454963453907530667147829489881
    180: 48558529144435440119720805669229197641
    181: 78569350599398894027251472817058687522
    182: 127127879743834334146972278486287885163
    183: 205697230343233228174223751303346572685
    

    Notice:

    While num_bigint::BigInt is 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.