Thursday, December 7, 2023
HomeSoftware EngineeringThe best way to discover the variety of trailing zeros of N...

# The best way to discover the variety of trailing zeros of N in Rust

## The problem#

Write a program that may calculate the variety of trailing zeros in a factorial of a given quantity.

`N! = 1 * 2 * 3 * ... * N`

Watch out `1000!` has 2568 digits…

## Examples#

``````zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero

zeros(12) = 2
# 12! = 479001600 --> 2 trailing zeros
``````

Choice 1:

``````fn zeros(n: u64) -> u64 {
if n == 0 { 0 }
else { n / 5 + zeros(n / 5) }
}
``````

Choice 2:

``````fn zeros(n: u64) -> u64  n / 5_u64.pow(exp))
.take_while(
``````

Choice 3:

``````fn zeros(n: u64) -> u64  acc + n / 5_u64.pow(i))

``````

## Check circumstances to validate our answer#

``````#[cfg(test)]
mod exams {
use tremendous::*;

#[test]
fn fixed_tests() {
assert_eq!(zeros(0), 0);
assert_eq!(zeros(6), 1);
assert_eq!(zeros(14), 2);
assert_eq!(zeros(30), 7);
assert_eq!(zeros(1000), 249);
assert_eq!(zeros(100000), 24999);
assert_eq!(zeros(1000000000), 249999998);
}

fn answer(n: u64) -> u64 {
let mut r = 0;
let mut n = n / 5;
whereas n > 0 {
r += n;
n /= 5;
}
r
}

use rand::Rng;

#[test]
fn random_tests() {

for _i in 0..100 {
let n: u64 = rng.gen_range(0..1001);
let precise = zeros(n);
assert_eq!(precise, anticipated, "zeros({}): anticipated {}, acquired {}", n, anticipated, precise);
}

for _i in 0..100 {
let n: u64 = rng.gen_range(0..1000001);
let precise = zeros(n);
assert_eq!(precise, anticipated, "zeros({}): anticipated {}, acquired {}", n, anticipated, precise);
}

for _i in 0..100 {
let n: u64 = rng.gen_range(0..1000000001);
let precise = zeros(n);
assert_eq!(precise, anticipated, "zeros({}): anticipated {}, acquired {}", n, anticipated, precise);
}
}
}
``````
RELATED ARTICLES