-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgcd.rs
71 lines (58 loc) · 1.53 KB
/
gcd.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
/**
* Greatest Common Divisor (GCD) or Highest Common Factor (HCF)
*
* The task is to find the GCD among numbers input in the console
*/
use common::input; // common library for this repository
fn divisors(num: usize) -> Vec<usize> {
let mut divisors: Vec<usize> = Vec::new();
for n in 1..=num / 2 {
if num % n == 0 {
divisors.push(n);
}
}
divisors.push(num);
return divisors;
}
fn gcd(mut list: Vec<usize>) -> usize {
list.sort();
// removing smallest of list to find divisors
let smallest = list.remove(0);
if smallest == 0 {
return 0;
};
// finding possible divisors of smallest number
let mut possible_divisors = divisors(smallest);
possible_divisors.sort();
possible_divisors.reverse();
for div in possible_divisors {
if list.iter().filter(|&f| f % div == 0).count() == list.len() {
return div;
};
}
return 1;
}
fn main() {
// ! input() is a common library function, not included in std
let numbers: Vec<usize> = input("Enter numbers separated by space: ")
.split(" ")
.map(|v| v.parse::<usize>().unwrap())
.collect();
println!("The GCD of {:?} is {}", numbers.clone(), gcd(numbers));
}
#[cfg(test)]
mod test {
use crate::gcd;
#[test]
fn _2_numbers() {
assert_eq!(gcd(vec![12, 18]), 6)
}
#[test]
fn _3_numbers() {
assert_eq!(gcd(vec![12, 18, 9]), 3)
}
#[test]
fn zero() {
assert_eq!(gcd(vec![12, 18, 9, 0]), 0)
}
}