A possible realization of brute force will be
head [n|n <- [1..], all ((==0).(n `mod`)) [1..20]]
but in this case it will take too much time. The all function checks if a predicate exists for all elements of the list. Lambda is short for (\d -> mod nd == 0) .
So, how could you speed up the calculation? Let our divisors factor in prime factors and look for the highest degree of each prime factor:
2 = 2 3 = 3 4 = 2^2 5 = 5 6 = 2 * 3 7 = 7 8 = 2^3 9 = 3^2 10 = 2 * 5 11 = 11 12 = 2^2*3 13 = 13 14 = 2 *7 15 = 3 * 5 16 = 2^4 17 = 17 18 = 2 * 3^2 19 = 19 20 = 2^2 * 5 -------------------------------- max= 2^4*3^2*5*7*11*13*17*19
Using this number, we have:
all ((==0).(2^4*3^2*5*7*11*13*17*19 `mod`)) [1..20] --True
Hey, it divides into all numbers from 1 to 20. Not very surprising. For instance. it is divided by 15 because it โcontainsโ factors 3 and 5, and it is divided by 16 because it โcontainsโ a factor of 2 ^ 4. But is this the smallest possible number? Think about it...
source share