Integer division is confusing

The rounding behaviour of integer division is counter-intuitive. Let's look at two examples that'll make you think.

Can you guess what the output of this program is?

				
					// Program A

fn main() {
    let a = 100;
    let b = 1000;

    println!("{}", a * (b/a));
    println!("{}", a * (a/b));
}
				
			

What about this one?

				
					// Program B

fn main() {
    let a = 1000;
    let b = 100;

    println!("{}",  a * (b/a));
    println!("{}", (a * b)/a);
}
				
			

ANSWERS

Program A

Hover or click to reveal output

1000 0

Visit Playground

Program B

Hover or click to reveal output

0 100

Visit Playground

Discussion

Integers don’t have decimal places, so rounding after division works differently than what you might be used to when doing a mathematical calculation.

Program A contains two important mathematical expressions, a * (b / a) and a * (a / b).

In the first expression, things work as expect. Given a = 100 and b = 1000, here is how those variables expand:

  • a * (a / b)        = x
  • 100 * (1000 / 100) = x
  • 100 * 10           = x
  • 1000               = x

In the second expression, things work the same, but different.

  • a * (a / b)        = x
  • 100 * (100 / 1000) = x
  • 100 * 0            = x
  • 0                  = x

When dealing with integers, there are no fractions, so the result of dividing by a number that is greater than the nominator is 0. Formally speaking, integer division returns the integer quotient.

 

Acknowledgements

Thanks to Marc Brooker for the reminder.

Contents