Search code examples
rustoperator-precedenceinteger-divisionassociativity

Why does x = x * y / z give a different result from x *= y / z for integers?


I have the following function:

pub fn s_v1(n: &u64) -> u64 {
    let mut x: u64 = 1;

    for i in 1..=*n  {
        x = x * (*n + i) / i;
    }

    x
}

This code gives the correct answer for s_v1(&20) == 137846528820

However, if I change the line in the for loop to x *= (*n + i) / i;

The answer changes to s_v1(&20) == 16094453760

Why are the results different? Isn't x = x * y the same as x *= y ?


Solution

  • Because * and / have the same precedence with left associativity, the expression is not

    x * ((*n + i) / i)
    

    (which is the same as x *= (*n + i) / i) but

    (x * (*n + i)) / i