Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating prime numbers in Rust

Tags:

rust

I am trying to calculate prime numbers in Rust but having some issues. I getting two errors. I am not understanding how the value is returning to the main function.

fn main() {
    let x = is_prime(25); //function calling
    println!("{}", x);
}

fn is_prime(n: u32) -> bool {
    let mut result: bool = for a in 2..n {
        result = if n % a == 0 { false } else { true };
    };
    result
}
error[E0425]: cannot find value `result` in this scope
 --> src/main.rs:8:9
  |
8 |         result = if n % a == 0 { false } else { true };
  |         ^^^^^^ not found in this scope
help: possible candidates are found in other modules, you can import them into scope
  |
1 | use futures::future::result;
  |
1 | use tokio::prelude::future::result;
  |

error[E0308]: mismatched types
 --> src/main.rs:7:28
  |
6 |   fn is_prime(n: u32) -> bool {
  |                          ---- expected `bool` because of return type
7 |       let mut result: bool = for a in 2..n {
  |  ____________________________^
8 | |         result = if n % a == 0 { false } else { true };
9 | |     };
  | |_____^ expected bool, found ()
  |
  = note: expected type `bool`
             found type `()`
like image 297
Muhammad Areeb Siddiqui Avatar asked Sep 19 '25 21:09

Muhammad Areeb Siddiqui


2 Answers

The problem with your code is that you are using the variable result while defining it

...
let mut result: bool = for a in 2..n { // declared here
    result = if n % a == 0 { // used here, but it is still not initialized
...

You can easily do without the result variable, is not necessary:

fn is_prime(n: u32) -> bool {
    if n <= 1 {
        return false;
    }
    for a in 2..n {
        if n % a == 0 {
            return false; // if it is not the last statement you need to use `return`
        }
    }
    true // last value to return
}

Playground link

like image 189
Netwave Avatar answered Sep 23 '25 12:09

Netwave


You have several issues in your code (ignoring that it does not compile):

  • you overwrite the result -> imagine n = 4. When you divide by 2 you get result = true, but in the next iteration when you divide by 3 you get result = false
  • if n<=2 your loop will never be executed, hence what will result be

Instead of trying to use any new piece of syntax, try to write it to be as readable as possible:

fn is_prime(n: u32) -> bool {
    let limit = (n as f64).sqrt() as u32;

    for i in 2..=limit {
        if n % i == 0 {
            return false;
        }
    }

    true
}
like image 42
Svetlin Zarev Avatar answered Sep 23 '25 12:09

Svetlin Zarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!