-
Notifications
You must be signed in to change notification settings - Fork 0
/
factorization_298.rs
79 lines (73 loc) · 1.89 KB
/
factorization_298.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
70
71
72
73
74
75
76
77
78
79
use std::collections::BTreeMap;
pub fn main() {
let n = get_num();
let factors = get_factors(n);
let size = factors.len();
for factor in factors.iter().enumerate() {
if *factor.1.1 == 1 {
print!("{}", factor.1.0);
} else {
print!("{}^{}", factor.1.0, factor.1.1);
}
if factor.0 != size - 1 {
print!("*")
}
}
}
fn get_num() -> i32 {
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap_or_default();
input.trim().parse().unwrap_or_default()
}
fn get_factors(mut n: i32) -> BTreeMap<i32, i32> {
let mut factors = BTreeMap::new();
if !is_prime(n) {
let root = (n as f32).sqrt() as i32;
while n > 1 {
if is_prime(n) {
match factors.get_mut(&n) {
None => {
factors.insert(n, 1);
}
Some(item) => {
*item = *item + 1;
}
}
break;
}
for i in 2..=root {
if is_prime(i) && n % i == 0 {
n = n / i;
match factors.get_mut(&i) {
None => {
factors.insert(i, 1);
}
Some(item) => {
*item = *item + 1;
}
}
}
}
}
} else {
factors.insert(n, 1);
}
factors
}
fn is_prime(n: i32) -> bool {
if n < 2 {
return false;
} else if n == 2 {
return true;
} else if n % 2 == 0 {
return false;
} else {
let root = (n as f32).sqrt() as i32;
for i in 3..=root {
if n % i == 0 {
return false;
}
}
}
true
}