Friday, November 9, 2018

Q8:Number of trailing zeros of N!

Question8 : Write a program that will calculate the number of trailing zeros in a factorial of a given number.

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

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

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

Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.

3 comments:

  1. from functools import reduce
    inp_val = int(input("Enter the number: "))
    ori_val = str(reduce(lambda x, y: x*y, list(range(1, inp_val+1))))
    number_of_trailing_zeros = len(ori_val) - len(ori_val.rstrip('0'))
    output = '%s trailing zero' if number_of_trailing_zeros == 1 else '%s trailing zeros'
    print(output%number_of_trailing_zeros)

    ReplyDelete
  2. from functools import reduce
    def zeros(n):
    if n>0:
    a=str(reduce(lambda x,y:x*y,range(1,(n+1))))
    print(a.count('0')-a.rstrip('0').count('0'))
    else:
    print(0)
    zeros(int(input()))

    ReplyDelete
  3. # import math
    # factorial = math.factorial(number)
    # or
    number = 70
    fact = lambda n: 1 if n == 0 else n*fact(n-1)
    factorial = fact(number)
    #method1:
    count = 0
    for n in str(factorial)[::-1]:
    if not n == '0':
    break
    count += 1
    print(f"Total number of trailing zero in factorial({number})={factorial} is {count}")

    ReplyDelete