[Haskell-cafe] Prime numbers

Daniel Carrera daniel.carrera at zmsl.com
Tue Dec 20 10:45:09 EST 2005


Hello all,

Trying to learn Haskell here... In a Haskell tutorial I found a function 
deciding if a number is prime:
--//--
prime n = not (factors 2 n)

factors m n | m == n = False
             | m < n  = divides m n || factors (m+1) n

divides a b = (mod a b == 0)
--//--

Reference:

http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/Function%20Definition%20by%20Cases%20and%20Recursion/sld038.htm

This function seems to produce a wrong result on the number 38466629 
(warning, slow computation). This number is prime but the function says 
that it's not.

How do I know that 38466629 is prime? Beause:

* http://www.rsok.com/~jrm/printprimes.html says that it is.
* I wrote another prime function that says that it is.

This is my function:
--//--
prime 1 = False
prime 2 = True
prime n = filter (divides n) primes == []
               where numbers = [x | x <- [2..n-1], x*x <= n]
                     primes  = filter prime numbers

divides a b = (mod a b == 0)
--//--

I can't figure out what's wrong with the first one. Can anyone spot the 
problem? (I'm just curious - trying to learn Haskell).

Cheers,
Daniel.
-- 
      /\/`) http://oooauthors.org
     /\/_/  http://opendocumentfellowship.org
    /\/_/
    \/_/    I am not over-weight, I am under-tall.
    /


More information about the Haskell-Cafe mailing list