mich abay
mich abay

Reputation: 13

Multiply with overflow: Rust Runtime error

In the Rust program, I'm trying to write I'm required to multiply 2 u64s and count the number of 1s when the product is represented as binary.

// Intentionally left uninitialized
let some_u64: u64;
let another_u64: u64;
let product = some_u64 * another_u64;

This operation will result in this "data type" for the product variable - (I'm not sure exactly what it is).

<u64 as Mul<u64>>::Output

When compiling this, it doesn't return any errors. However, when running it, it returns the following error.

thread 'main' panicked at 'attempt to multiply with overflow', src/file.rs:67:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

With the RUST_BACKTRACE=1 environment variable

thread 'main' panicked at 'attempt to multiply with overflow', src/magics.rs:67:23
stack backtrace:
   0: rust_begin_unwind
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:575:5
   1: core::panicking::panic_fmt
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:65:14
   2: core::panicking::panic
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:115:5
   3: rust_chess::magics::find_magics
             at ./src/file.rs:67:23
   4: rust_chess::magics::init
             at ./src/file.rs:10:13
   5: rust_chess::main
             at ./src/main.rs:11:5
   6: core::ops::function::FnOnce::call_once
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/ops/function.rs:251:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

What should I do in order to multiply 2 u64s and use the product without having runtime errors?

FYI, I've tried to cast it to u128, which unfortunately led to the same result.

EDIT: Here is a playground link to see a minimal reproducible example.

Upvotes: 0

Views: 831

Answers (1)

kmdreko
kmdreko

Reputation: 59942

You can convert your u64s into u128s before multiplying them to avoid an overflow:

let some_num: u64 = 36670911850479872;
let another_num: u64 = 18049651735527936;

let product = u128::from(some_num) * u128::from(another_num);

println!("{} * {} = {}", some_num, another_num, product);
36670911850479872 * 18049651735527936 = 661897187725405976746072861704192

Upvotes: 2

Related Questions