Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, count the trailing zeros within a factorial

I am trying to calculate the number of trailing zeros in a factorial.

def count(x):
    zeros = 0                     
    for i in range (2,x+1): 
        print(i)
        if x > 0:
            if i % 5 == 0:       
                print("count")    
                zeros +=1       
        else:
            ("False")
    print(zeros)        

count(30)

I think the number of trailing zeros is incorrect.

When using count(30), there are 7 trailing 0's in 30. However it is returning 6.

like image 242
Oscar Dolloway Avatar asked Jan 05 '23 01:01

Oscar Dolloway


1 Answers

def count (x):
    i = 5
    zeros = 0
    while x >= i:
        zeros += x // i
        i *= 5
    return zeros

print(count(30))
like image 112
John Smith Avatar answered Jan 14 '23 14:01

John Smith