-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon_prime_divisors.rs
69 lines (62 loc) · 1.68 KB
/
common_prime_divisors.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
struct CommonPrimeDivisors;
impl CommonPrimeDivisors {
fn gcd(a: i32, b: i32, res: i32) -> i32 {
if a == b {
res * a
} else if (a % 2 == 0) & (b % 2 == 0) {
CommonPrimeDivisors::gcd(a / 2, b / 2, 2 * res)
} else if a % 2 == 0 {
CommonPrimeDivisors::gcd(a / 2, b, res)
} else if b % 2 == 0 {
CommonPrimeDivisors::gcd(a, b / 2, res)
} else if a > b {
CommonPrimeDivisors::gcd(a - b, b, res)
} else {
CommonPrimeDivisors::gcd(a, b - a, res)
}
}
fn has_same_prime_divisors(mut a: i32, mut b: i32) -> bool {
let gcd_value = CommonPrimeDivisors::gcd(a, b, 1);
let mut gcd_a;
let mut gcd_b;
while a != 1 {
gcd_a = CommonPrimeDivisors::gcd(a, gcd_value, 1);
if gcd_a == 1 {
break;
}
a = a / gcd_a;
}
if a != 1 {
return false;
}
while b != 1 {
gcd_b = CommonPrimeDivisors::gcd(b, gcd_value, 1);
if gcd_b == 1 {
break;
}
b = b / gcd_b;
}
return b == 1;
}
fn solution(a: &Vec<i32>, b: &Vec<i32>) -> i32 {
let n = a.len();
let mut count = 0;
for i in 0..n {
if CommonPrimeDivisors::has_same_prime_divisors(a[i], b[i]) {
count += 1;
}
}
count
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_common_prime_divisors() {
assert_eq!(
CommonPrimeDivisors::solution(&vec![15, 10, 3], &vec![75, 30, 5]),
1
);
}
}