PDA

View Full Version : Haskell: factoring into primes



danbaron
12-06-2011, 08:47
"ghci" means, "Glasgow Haskell Compiler Interactive".

Below, I used ghci, but, you can also use "ghc", which is the compiler.

http://www.haskell.org/haskellwiki/Haskell

http://www.haskell.org/haskellwiki/Tutorials


' code ------------------------------------------------------------------------------------------------

-- file = "factors.hs"
-- from, "The Haskell Road to Logic, Maths and Programming", Doets, Eijk, 2004.

divides :: Integer -> Integer -> Bool
divides d n = rem n d == 0

ld :: Integer -> Integer
ld n = ldf 2 n

ldf :: Integer -> Integer -> Integer
ldf k n | divides k n = k
| k^2 > n = n
| otherwise = ldf (k+1) n

factors :: Integer -> [Integer]
factors n | n < 1 = error "argument not positive"
| n == 1 = []
| otherwise = p : factors (div n p) where p = ld n

' ghci interactions -----------------------------------------------------------------------------------

C:\Users\root\Desktop\Haskell>ghci
GHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude> :load factors.hs
[1 of 1] Compiling Main ( factors.hs, interpreted )
Ok, modules loaded: Main.
*Main> factors 1
[]
*Main> factors 2
[2]
*Main> factors 64
[2,2,2,2,2,2]
*Main> factors 2768
[2,2,2,2,173]
*Main> factors 23968
[2,2,2,2,2,7,107]
*Main> factors 483753
[3,113,1427]
*Main> factors 6847201
[19,557,647]
*Main> factors 58396833
[3,3,11,41,14387]
*Main> factors 297857437
[37,37,217573]
*Main> factors 9784632367
[9784632367]
*Main> factors 28574633901
[3,11,23,37647739]
*Main> factors 656898746323
[1583,414970781]
*Main> factors 3867563542911
[3,37,34842914801]
*Main> factors 49274657327589
[3,41,400606970143]
*Main> factors 296857462546113
[3,7,14136069645053]
*Main> factors 5385763508908301
[71,1471,51567521461]
*Main> factors 37162536487960499
[7,11,31,31,79,6357174673]
*Main> factors 368463261532687951
[7,

^
|
|

It only got started on the last one, I didn't want to wait.