the number of trailing zeros in a factorial of a given number - Ruby

后端 未结 12 1924
执念已碎
执念已碎 2020-12-11 03:37

Having a little trouble trying calculate the number of trailing zeros in a factorial of a given number. This is one of the challenges from Codewars- can\'t get mine to pass.

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 04:18

    As per the explanation given by @spundan and apart from @cary's code you can find number of trailing zero by just very simple and efficient way..see below code..

    def zeros(n)
        ret = 0
        while n > 0 do 
            ret += n / 5
            n = n/5
        end
        ret
    end
    

    For example zeros(100000000) this will give you output -> 24999999
    With the time Time Elapsed -> 5.0453e-05(Just See 5.0453e-05 )
    This is the part of even milliseconds.

提交回复
热议问题