---
title: "Create a Rust program to determine if a number is prime or not."  
description: "Create a Rust program to determine if a number is prime or not."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-24  
canonical: https://www.mindstick.com/forum/158797/create-a-rust-program-to-determine-if-a-number-is-prime-or-not  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Create a Rust program to determine if a number is prime or not.

Create a [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) [program to determine](https://www.mindstick.com/forum/158836/write-a-rust-program-to-determine-if-a-given-matrix-is-symmetric-or-not) if a number is prime or not.

## Replies

### Reply by Aryan Kumar

Sure, here is a [Rust program](https://www.mindstick.com/forum/158800/create-a-rust-program-to-find-the-gcd-greatest-common-divisor-of-two-numbers) to determine if a number is prime or not:

Rust

```plaintext
fn is_prime(number: i32) -> bool {
  // Check if the number is less than 2.
  if number < 2 {
    return false;
  }

  // Iterate over all numbers from 2 to the square root of the number.
  for i in 2..(number as f64).sqrt() as i32 + 1 {
    // Check if the number is divisible by any of the numbers.
    if number % i == 0 {
      // The number is not prime.
      return false;
    }
  }

  // The number is prime.
  return true;
}

fn main() {
  // Get the number from the user.
  let mut number = String::new();
  io::stdin().read_line(&mut number).unwrap();

  // Convert the number to an integer.
  let number: i32 = number.trim().parse().unwrap();

  // Check if the number is prime.
  let is_prime = is_prime(number);

  // Print the result.
  if is_prime {
    println!("The number {} is prime.", number);
  } else {
    println!("The number {} is not prime.", number);
  }
}
```

This program first checks if the number is less than 2. If it is, then the program returns false. Otherwise, the program iterates over all numbers from 2 to the square root of the number. For each number in the loop, the program checks if the number is divisible by the current number. If the number is divisible by the current number, then the program returns false. Finally, the program returns true if the number is not divisible by any of the numbers.

To run this program, you can save it as a `.rs` file and then compile and run it using the following commands:

Code snippet

```plaintext
rustc is_prime.rs
./is_prime
```

This will prompt you to enter a number. Enter a number and press Enter. The program will then print whether the number is prime or not.


---

Original Source: https://www.mindstick.com/forum/158797/create-a-rust-program-to-determine-if-a-number-is-prime-or-not

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
