计算Rust中的质数

时间:2019-04-22 07:11:07

标签: rust

我正在尝试在Rust中计算素数,但是有一些问题。我遇到两个错误。我不明白该值如何返回到主函数。

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 `()`

2 个答案:

答案 0 :(得分:2)

代码的问题是您在定义变量时使用变量result

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

您可以轻松地使用result变量,这是不必要的:

fn is_prime(n: u32) -> bool {
    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

答案 1 :(得分:2)

您的代码中有几个问题(忽略它不会编译):

  • 您覆盖了结果->想象n = 4。当您除以2时,您会得到result = true,但是在下一次迭代中,如果您除以3时,您会得到result = false
  • 如果n<=2将永远不会执行,那么结果将是

不要尝试使用任何新的语法,而应尝试使其尽可能可读:

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
}