Complete the code to check if a number is less than 2, which means it is not prime.
fn is_prime(n: u32) -> bool {
if n [1] 2 {
return false;
}
true
}If the number is less than 2, it is not prime. So we return false.
Complete the code to loop from 2 up to the square root of the number to check for divisors.
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
let limit = (n as f64).sqrt() as u32;
for i in 2..=[1] {
if n % i == 0 {
return false;
}
}
true
}We only need to check divisors up to the square root of n, stored in 'limit'.
Fix the error in the code to correctly return false if a divisor is found.
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
let limit = (n as f64).sqrt() as u32;
for i in 2..=limit {
if n % i [1] 0 {
return false;
}
}
true
}We return false if n is divisible by i, which means n % i == 0.
Fill both blanks to complete the function that checks if a number is prime.
fn is_prime(n: u32) -> bool {
if n [1] 2 {
return false;
}
let limit = (n as f64).sqrt() as u32;
for i in 2..=[2] {
if n % i == 0 {
return false;
}
}
true
}The function returns false if n is less than 2, and loops up to 'limit' to check divisors.
Fill all three blanks to create a function that checks if a number is prime efficiently.
fn is_prime(n: u32) -> bool {
if n [1] 2 {
return false;
}
let limit = (n as f64).[2]() as u32;
for i in 2..=[3] {
if n % i == 0 {
return false;
}
}
true
}The function returns false if n is less than 2, calculates the square root as 'limit', and loops up to 'limit' to check divisors.
