How to check if the given number is a prime number in Rust
Rust
x
38
fn main() {
let mut number = 0;
println!("Enter a number: ");
std::io::stdin().read_line(&mut number).expect("Failed to read line");
let number: u32 = match number.trim().parse() {
Ok(num) => num,
Err(_) => 0,
};
if is_prime(number) {
println!("{} is a prime number", number);
} else {
println!("{} is not a prime number", number);
}
fn is_prime(n: u32) -> bool { // function to check if the given number is prime or not.
if n <= 1 { // If the given value is less than or equal to 1, it is not prime.
return false;
🤖 Code Explanation
The code first prompts the user to enter a number. It then tries to parse the input as a 32-bit unsigned integer. If it succeeds, the number is stored in the variable "number". If it fails, the number 0 is stored instead.
Next, the code calls the function "is_prime" to check if the number is prime. If it is, the code prints a message saying so. If it isn't, the code prints a message saying so.