Saturday, October 20, 2012

Mathematics13

Q13. Write an algorithm which computes the number of trailing zeros in n factorial.
Answer:

public class Mathematics13 {
    public static int getTrailingZeroes(int n) {
        if (n < 0) {
            System.out.println("Factorial is not defined for negative numbers");
            return 0;
        }

        int count = 0;
        for (int i = 5; n / i > 0; i *= 5) {
            count += n / i;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println("Number of trailing zeroes in 10! : "
                + getTrailingZeroes(10));
        System.out.println("Number of trailing zeroes in 100! : "
                + getTrailingZeroes(100));
        System.out.println("Number of trailing zeroes in 125! : "
                + getTrailingZeroes(125));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.