Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how often I can divide

The following function counts how often I can divide one number by another:

divs n p = if (n `mod` p == 0) then 1 + divs (n `div` p) p else 0

Is there a shorter way to write divs?

like image 378
foobar Avatar asked Mar 19 '26 10:03

foobar


1 Answers

My variant would be:

factors :: Integral i => i -> i -> Int
factors f =
    length . takeWhile (== 0) .
    map (`mod` f) . iterate (`div` f)

The iterate/map pattern is very useful for many problems.

like image 97
ertes Avatar answered Mar 22 '26 05:03

ertes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!