You probably know about project Euler question 5: get the smallest number divisble by all numbers 1 to 20.
The logic I applied was “start with the first number greater than the largest of the list(20) and also divisible by it which is 40” and stepsize of 20 (largest number)
I did this using list comprehension but it’s pretty lame.
pe5 = head [x|x<-[40,60..],x`mod`3==0,x`mod`4==0,x`mod`6==0,x`mod`7==0,x`mod`8==0,x`mod`9==0,x`mod`11==0,x`mod`12==0,x`mod`13==0,x`mod`14==0,x`mod`15==0,x`mod`16==0,x`mod`17==0,x`mod`18==0,x`mod`19==0]
Can we do this better perhaps using zipWith and filter maybe?
Just to clarify, this is not a homework assignment. I’m doing this to wrap my brain around Haskell. (So far I’m losing!)
:Thanx all
I think this is a saner way (there may be thousand more better ways but this would suffice) to do it
listlcm'::(Integral a)=> [a] -> a
listlcm' [x] = x
listlcm' (x:xs) = lcm x (listlcm' xs)
Yes, you can do much better. For starters, rewrite to something like
But what you really need here is not slicker Haskell, but a smarter algorithm. Hint: use the Fundamental Theorem of Arithmetic. Your Haskell solution would then start with the standard sieve-of-Eratosthenes example.