当前位置: 代码迷 >> 综合 >> Rust 练习:求一组数的最大公约数
  详细解决方案

Rust 练习:求一组数的最大公约数

热度:89   发布时间:2023-12-12 15:25:39.0

下面程序求解若干自然数的最大公约数,自然数放在命令行中输入,源代码如下:

use std::io::Write;
use std::str::FromStr;fn gcd(mut x: u64, mut y: u64) -> u64 {
    loop {
    if x == y {
     break; }if x > y {
     x = x - y; }if x < y {
     y = y - x; }}x
}fn main() {
    let mut numbers = Vec::new();for arg in std::env::args().skip(1){
    numbers.push(u64::from_str(&arg).expect("error parsing argment"));}if numbers.len() == 0 {
    writeln!(std::io::stderr(), "Usage: gcd Number ...").unwrap();std::process::exit(1);}let mut d = numbers[0];for m in &numbers[1..] {
    d = gcd(d, *m);}println!("The greatest common divisor of {:?} is {}", numbers, d);
}

运行一下,有如下结果:

$ cargo run  45 9 81 27Compiling testweb v0.1.0 (/home/yeping/testweb)Finished dev [unoptimized + debuginfo] target(s) in 0.31sRunning `/home/.../gcd 45 9 81 27`
The greatest common divisor of [45, 9, 81, 27] is 9