mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-22 00:23:47 +01:00
4kyu: add factorial tail
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1f4adef5e6
commit
85b94313f6
2 changed files with 61 additions and 0 deletions
60
4kyu/factorial_tail/solution.rs
Normal file
60
4kyu/factorial_tail/solution.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
type Factors = HashMap<i32, i32>;
|
||||
|
||||
fn as_primes(mut n: i32) -> Factors {
|
||||
let mut powers: Factors = HashMap::new();
|
||||
|
||||
(2..((n as f64).sqrt() as i32) + 1).for_each(|x| {
|
||||
let mut q = 0;
|
||||
while n % x == 0 {
|
||||
n /= x;
|
||||
q += 1;
|
||||
}
|
||||
|
||||
if q != 0 {
|
||||
powers.insert(x, q);
|
||||
}
|
||||
});
|
||||
|
||||
if n > 1 {
|
||||
powers.insert(n, 1);
|
||||
}
|
||||
|
||||
powers
|
||||
}
|
||||
|
||||
fn get_powers(m: i32, primes: HashSet<&i32>) -> Factors {
|
||||
let mut powers: Factors = HashMap::new();
|
||||
|
||||
(2..m + 1).for_each(|mut n| {
|
||||
primes.iter().for_each(|&&x| {
|
||||
let mut q = 0;
|
||||
while n % x == 0 {
|
||||
n /= x;
|
||||
q += 1;
|
||||
}
|
||||
|
||||
powers.insert(x, q + powers.get(&x).unwrap_or(&0));
|
||||
});
|
||||
});
|
||||
|
||||
powers
|
||||
}
|
||||
|
||||
fn get_zeroes(base: Factors, powers: Factors) -> i32 {
|
||||
let mut adjusted: Factors = HashMap::new();
|
||||
|
||||
for (prime, power) in powers {
|
||||
adjusted.insert(prime, power / base[&prime]);
|
||||
}
|
||||
|
||||
*adjusted.values().min().unwrap()
|
||||
}
|
||||
|
||||
fn zeroes(base: i32, number: i32) -> i32 {
|
||||
let base_as_primes = as_primes(base);
|
||||
let powers: Factors = get_powers(number, base_as_primes.keys().collect());
|
||||
get_zeroes(base_as_primes, powers)
|
||||
}
|
|
@ -17,6 +17,7 @@
|
|||
### Rust
|
||||
|
||||
- [Sum by Factors](https://www.codewars.com/kata/54d496788776e49e6b00052f) - [solution](4kyu/sum_by_factors)
|
||||
- [Factorial tail](https://www.codewars.com/kata/55c4eb777e07c13528000021) - [solution](4kyu/factorial_tail)
|
||||
|
||||
### C#
|
||||
|
||||
|
|
Loading…
Reference in a new issue