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 `()`
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
You have several issues in your code (ignoring that it does not compile):
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
n<=2
your loop will never be executed, hence what will result beInstead 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With