ShareMyScreen/QuoraQuestions/2025/01/TrailingZeros

From J Wiki
Jump to navigation Jump to search

Let where and are both positive integers. Find the number of trailing zeros of p(N).

Skip began with a plain, brute force solution to encourage Forum participation.

   (<:#p)->./I.p=.-.'0'=":*/! >: i.1000x
123124


Henry responded by showing off Raul's work in overhauling JE's extended arithmetic with a leaner solution. Counting 5s with q: and = .

   NB. #factors of 5 per integer, then accumulate # of times each one appears in product
   (|. +/@:*"1 #\) 5&(+/@:=)@q:"0 >: i. 1000
123124


Then, came Marshall's short one-liner; adding up after repeated divisions of 5.

   +/,1}.<.@%&5^:a:i.1001
123124


Maurice wanted a solution to scale reasonably well in time and space if N were much larger. He used divisions of power of 5s, but added ^. to reduce zeros.

   f =: 5 ^ [: >: [: i. [: (<.) 5 ^. ]
   +/ +/@:<.@:(] % f)"0 ] >: i.1000
123124


Mike looked at Maurice's solution, and felt his repeated divisions of the power of 5s could be eliminated while keeping the memory footprint at bay.

   mdc =: {{
'fivep t num' =. y
if. num < fivep =. 5 * fivep do.
   y
else.
   fivep, num ,~ t + (div * >: fivep|num) +  fivep * (-:<.@*<:) div =. num <.@% fivep   
end.
}}

   NB. cover function
   domdc =: 1{(mdc^:_)@:(1 0,])
   domdc 1000
123124


Finally, Marcin offered a Tacit version using the approach similar to Mike's but do all power of 5s divisions together after generating them using u^:v^:a: .

   f=:(>:+/@:-:@(<.@%*-+|~)5&*@]^:>:^:a:&5x)"0
   f 1000
123124


However, only Mike's and Marcin's could be pushed to the extreme.

   s=: ". '1' , (1e3 $ '0') , 'x' NB. 1001-digit number.
   timespacex 'domdc s'
0.009868 8600
    timespacex 'f s'
0.005493 2.44313e6


Closing thought?

Even something as simple as the following is adequate for the stated problem. But it just amazing how far the Forum members pushed it.

    +/,5=q:!>:i.1000x
123124


Original Trailing Zeros J Forum Thread