Skip to content

Use std::mem::swap instead of temp variables #4

@claytonwramsey

Description

@claytonwramsey

Hi! I just came across your website from the Rust Users forum. It's pretty cool!

I noticed a spot where the code provided for Euclid's GCD algorithm could be improved: you use temporary variables to swap a and b, but we can just use std::mem::swap to more idiomatically (and maybe slightly more quickly) swap the two.

Here's what the simplified code would be:

fn gcd(mut a: usize, mut b: usize) -> usize {
    // If equal, return any of them
    if a == b {
        return a;
    }

    // Swap a with b, if b is greater than a
    if b > a {
        std::mem::swap(&mut a, &mut b);
    }

    while b > 0 {
        a %= b;
        std::mem::swap(&mut a, &mut b);
    }

    // Now, a % b = 0, hence return it
    return a;
}

(I would also substitute the first two checks with match a.cmp(&b) to save time, but this is mostly a matter of taste)

While we're at it, it might be worthwhile that most modern implementations of GCD these days take advantage of O(1) bit-scan operations - in the case of Rust, trailing_zeros() - to quickly implement the binary GCD algorithm. Check out how num does it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions