Rust Iterators A short primality test


Example

fn is_prime(n: u64) -> bool {
    (2..n).all(|divisor| n % divisor != 0)
}

Of course this is isn't a fast test. We can stop testing at the square root of n:

(2..n)
    .take_while(|divisor| divisor * divisor <= n)
    .all(|divisor| n % divisor != 0)