var | desc |
---|---|
Number to factorialize: |
A factorial
For example
One approach would be to check if the result of factorial
let mut fac: u128 = (1..=n).product();
let mut cnt = 0;
while fac % 10 == 0 { cnt += 1; fac /= 10; }
println!("Trailing zeros: {cnt}");
But this approach is pretty slow and could lead to integer overflow when dealing with big numbers.
10 can be factorized by prime numbers 2 and 5:
So we have to check for 2 and 5 pairs in the factorial equation. Because there will be more 2's than 5's we can look for 5's only.
By the way,
Here we have one time
So we check how many times res
and then divide
In Rust 🦀 code:
fn main() {
let mut n: u64 = std::io::read_to_string(std::io::stdin())
.unwrap()
.trim()
.parse()
.unwrap();
let mut res = 0;
while n > 0 { res += n / 5; n /= 5; }
println!("{res}");
}