So, I'm admittedly a Haskell Newbie, but I so far like it a lot since I've been on a prime number splurge lately. (Which is what turned me on to it)
I've got this relatively basic script. It works exactly as it should, even if it's not as efficient as possible. That's not my question though. Here is my script:
import System.Environment
oddFactors p = [x | x<- [3,5..floor (sqrt (fromIntegral p))], p `mod` x == 0]
prime x = oddFactors (2^x -1) == []
main = do
args <- getArgs
print (prime (read (head args) :: Int))
Like I said, simple. oddFactors
goes through odd numbers from 3
to sqrt(p)
and adds it to a list if it was a factor of p.
primes
calls oddFactor
s on 2^x -1
and checks if the resulting list is equal to the empty list.
The weird thing is, it appears to already be optimized. In the case of primes
if I were to do, for example, 61, my program takes 49 seconds to run and returns True. If I do 60 or 62, though, it takes .005s to run and returns False. These are the correct return values, but I'm curious if it's optimized somehow since it knows it's only looking for a list matching [] and after finding one, it returns false, since the list will never be []
Long winded question, but I'm also willing to take any suggestions on my code so far. I picked Haskell up about two hours ago, so be nice :)
EDIT: I of course know I can use something better as a primality test, such as Miller-Rabin, but that's not the point ;)