w3resource

Rust Function: Check Prime number

Rust Functions and Control Flow: Exercise-2 with Solution

Write a Rust function to check if a number is prime.

Sample Solution:

Rust Code:

// Define a function named 'is_prime' that takes a number as parameter and returns true if it's prime, false otherwise
fn is_prime(num: u64) -> bool {
    if num <= 1 {
        return false; // Numbers less than or equal to 1 are not prime
    }
    
    // Check if num is divisible by any number from 2 to the square root of num
    for i in 2..=(num as f64).sqrt() as u64 {
        if num % i == 0 {
            return false; // If num is divisible by any number other than 1 and itself, it's not prime
        }
    }
    
    true // If num is not divisible by any number other than 1 and itself, it's prime
}

fn main() {
    let num = 17; // Define the number to be checked for primality

    // Call the 'is_prime' function to check if 'num' is prime
    if is_prime(num) {
        println!("{} is prime", num);
    } else {
        println!("{} is not prime", num);
    }
}

Output:

17 is prime

Explanation:

Here's a brief explanation of the above Rust code:

  • 'fn is_prime(num: u64) -> bool { ... }': This is a function named 'is_prime' that takes a single parameter 'num' of type 'u64' (unsigned 64-bit integer) and returns a boolean indicating whether the number is prime ('true') or not ('false').
  • 'if num <= 1 { return false; }': This line checks if the number is less than or equal to 1, which is not prime. If so, the function returns 'false'.
  • 'for i in 2..=(num as f64).sqrt() as u64 { ... }': This line iterates from 2 to the square root of the number ('num') to check if it's divisible by any number other than 1 and itself.
  • 'if num % i == 0 { return false; }': This line checks if the number is divisible by 'i'. If it is, the function immediately returns 'false', indicating that the number is not prime.
  • 'true': If the number is not divisible by any number other than 1 and itself, the function returns 'true', indicating that the number is prime.
  • In the 'main' function, we define a number ('num') to check whether the number is prime or not. We then call the 'is_prime' function with this number and print whether it is prime or not.

Rust Code Editor:

Previous: Rust Function: Calculate rectangle area.
Next: Rust Program: Find maximum and minimum in array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.