Friday, May 26, 2023
HomeSoftware EngineeringLearn how to discover the variety of trailing zeros of N in...

Learn how 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…

For more information, see: http://mathworld.wolfram.com/Factorial.html

Examples

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

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

The answer in Rust

Choice 1:

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

Choice 2:

fn zeros(n: u64) -> u64 exp

Choice 3:

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

Take a look at 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() {
        let mut rng = rand::thread_rng();
        
        for _i in 0..100 {
            let n: u64 = rng.gen_range(0..1001);
            let anticipated = answer(n);
            let precise = zeros(n);
            assert_eq!(precise, anticipated, "zeros({}): anticipated {}, bought {}", n, anticipated, precise);
        }
        
        for _i in 0..100 {
            let n: u64 = rng.gen_range(0..1000001);
            let anticipated = answer(n);
            let precise = zeros(n);
            assert_eq!(precise, anticipated, "zeros({}): anticipated {}, bought {}", n, anticipated, precise);
        }
        
        for _i in 0..100 {
            let n: u64 = rng.gen_range(0..1000000001);
            let anticipated = answer(n);
            let precise = zeros(n);
            assert_eq!(precise, anticipated, "zeros({}): anticipated {}, bought {}", n, anticipated, precise);
        }
    }    
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments