Rust Program to Check Whether a Number is Prime or Not

Check Whether a Number is Prime or Not

Rust Programming Language

Check Whether a Number is Prime or Not


Rust program that checks whether a given number is prime or not.


use std::io;

fn main() {
    println!("Please enter a positive integer:");

    let mut input = String::new();
        .read_line(&mut input)
        .expect("Failed to read line");

    let input = input.trim().parse::<u32>().unwrap();

    let mut is_prime = true;
    for i in 2..input {
        if input % i == 0 {
            is_prime = false;

    if is_prime {
        println!("The number {} is prime", input);
    } else {
        println!("The number {} is not prime", input);


Please enter a positive integer:
The number 17 is prime{codeBox}


This program prompts the user to enter a positive integer, reads the input integer from the user using the io module from Rust's standard library, and parses it into an unsigned 32-bit integer using parse::<u32>().unwrap().

We then initialize a boolean variable is_prime to true. We then iterate over all integers i from 2 up to (but not including) the input integer input. For each integer i, we check if input is divisible by i (i.e. input % i == 0). If it is, we set is_prime to false and break out of the loop.

Finally, we check the value of is_prime. If it is true, we print "The number [input] is prime" to the console. Otherwise, we print "The number [input] is not prime".

This shows the program prompting the user to enter a positive integer, the user entering the integer 17, and the program checking if the integer is prime (which it is), and displaying the appropriate message to the console.

Post a Comment