DEV Community

Shelner
Shelner

Posted on

Factorial Trailing Zeros

Solution code (Java)

public class FactorialTrailingZeros {
    public static int trailingZeros(int num) {
        int result = 0;
        int crrPowerOfFive = 5; // 5, 25, 125, 625, ...
        while (num >= crrPowerOfFive) {
            result += num / crrPowerOfFive;
            crrPowerOfFive *= 5;
        }
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Test Code (JUnit)

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class FactorialTrailingZerosTest {
    @Test
    void test3() {
        int testData = 3;
        int expected = 0;
        int result = FactorialTrailingZeros.trailingZeros(testData);
        assertEquals(expected, result);
    }

    @Test
    void test5() {
        int testData = 5;
        int expected = 1;
        int result = FactorialTrailingZeros.trailingZeros(testData);
        assertEquals(expected, result);
    }

    @Test
    void test24() {
        int testData = 24;
        int expected = 4;
        int result = FactorialTrailingZeros.trailingZeros(testData);
        assertEquals(expected, result);
    }

    @Test
    void test125() {
        int testData = 125;
        int expected = 25 + 5 + 1;
        int result = FactorialTrailingZeros.trailingZeros(testData);
        assertEquals(expected, result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution Code (TypeScript)

export function factorialTrailingZeros(num: number): number {
    let count = 0;
    let crrPowerOfFive = 5;
    while (num >= crrPowerOfFive) {
        count += Math.floor(num / crrPowerOfFive);
        crrPowerOfFive *= 5;
    }
    return count;
}
Enter fullscreen mode Exit fullscreen mode

Test Code (Jest)

describe("factorialTrailingZeros", () => {
    test("should return 0 for n = 0", () => {
        expect(factorialTrailingZeros(0)).toBe(0);
    });

    test("should return 0 for n = 4", () => {
        expect(factorialTrailingZeros(4)).toBe(0);
    });

    test("should return 1 for n = 5", () => {
        expect(factorialTrailingZeros(5)).toBe(1);
    });

    test("should return 6 for n = 25", () => {
        expect(factorialTrailingZeros(25)).toBe(6);
    });

    test("should return 31 for n = 125", () => {
        expect(factorialTrailingZeros(125)).toBe(31);
    });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)