-
Notifications
You must be signed in to change notification settings - Fork 0
/
factor.rs
69 lines (56 loc) · 1.31 KB
/
factor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::env;
use std::process::ExitCode;
fn min_div(n: i64) -> i64 {
let n0: i64 = n;
let mut divisor = 2;
while n0 != 1 {
if n0 % divisor == 0 {
break;
}
divisor += 1;
}
divisor
}
fn factor(n: i64) -> Vec<i64> {
let mut v = vec!();
let mut n0: i64 = n;
while n0 != 1 {
let divisor = min_div(n0);
v.push(divisor);
n0 /= divisor;
}
v
}
fn show_factors(n: i64) {
let factors = factor(n);
print!("{}: ", n);
for f in &factors {
print!("{} ", f);
}
println!();
}
fn main() -> ExitCode {
let args: Vec<String> = env::args().collect();
let program = &args[0];
if args.len() < 2 {
println!("{}: missing number to factorize", program);
return ExitCode::FAILURE;
}
let number = &args[1];
let parsed = number.parse::<i64>();
match parsed {
Ok(_) => {
let n = parsed.unwrap();
if n < 0 {
println!("{}: {} is not a valid positive integer", program, n);
return ExitCode::FAILURE;
}
show_factors(n);
},
_ => {
println!("{}: '{}' is not a valid number", program, number);
return ExitCode::FAILURE;
},
};
ExitCode::SUCCESS
}