fn is_prime(n: u32) -> bool { if n <= 1 { return false; } for i in 2..=((n as f64).sqrt() as u32) { if n % i == 0 { return false; } } true } fn main() { println!("{}", is_prime(29)); }
The function correctly checks divisors up to the square root of 29. Since 29 has no divisors other than 1 and itself, it returns true.
fn is_prime(n: u32) -> bool { if n <= 1 { return false; } for i in 2..=((n as f64).sqrt() as u32) { if n % i == 0 { return false; } } true } fn main() { println!("{}", is_prime(1)); }
The function returns false immediately for numbers less than or equal to 1, so it returns false for 1.
fn is_prime(n: u32) -> bool { if n <= 1 { return false; } for i in 2..(n as f64).sqrt() as u32 { if n % i == 0 { return false; } } true } fn main() { println!("{}", is_prime(25)); }
The range excludes the upper bound because it uses .. instead of ..=, so it misses checking divisor 5. But since 25 % 2 == 0 is false and 25 % 3 == 0 is false and 25 % 4 == 0 is false, the loop ends without finding divisor 5. So it incorrectly returns true. But the code actually returns true incorrectly.
fn is_prime(n: u32) -> bool { if n <= 1 { return false; } for i in 2..=((n as f64).sqrt() as u32) { if n % i == 0 { return false; } } true } fn main() { println!("{}", is_prime(0)); }
The function returns false immediately for numbers less than or equal to 1, so it returns false for 0.
If a number n has a divisor larger than its square root, it must be paired with a divisor smaller than the square root. So checking up to the square root is enough to find all divisors.
