Anonymous user
Miller–Rabin primality test: Difference between revisions
→{{header|Haskell}}
(No function doing the task) |
|||
Line 1,170:
=={{header|Haskell}}==
{{works with|Haskell|
* Ideas taken from [http://primes.utm.edu/prove/prove2_3.html Primality proving]
* Functions witns and isMillerRabinPrime follow closely the code outlined in [http://www.jsoftware.com/jwiki/Essays/Primality%20Tests#Miller-Rabin J/Essays]
* A useful powerMod function is taken from [[Multiplicative order#Haskell]]
* Original Rosetta code has been simplified to be easier to follow
Another Miller Rabin test can be found in D. Amos's Haskell for Math module [http://www.polyomino.f2s.com/david/haskell/numbertheory.html Primes.hs]
<lang Haskell>
import System.Random
import System.IO.Unsafe
-- Miller-Rabin wrapped up as an (almost deterministic) pure function
isPrime n = unsafePerformIO (isMillerRabinPrime n)
isMillerRabinPrime n
| even n = return (n==2)
| n < 100 = return (n `elem` primesTo100)
return $ and (map (test n (pred n)) ws)
test :: Integral nat => nat -> nat -> nat -> Bool
test n n_1 w = n_1 `elem` powers || last powers == 1
where
powers = map (powerMod n w) (evens ++ take 1 odds)
witnesses k n
| n < 9080191 = return [31,73]
| n < 4759123141 = return [2,7,61]
| n < 3474749660383 = return [2,3,5,7,11,13]
| n < 341550071728321 = return [2,3,5,7,11,13,17]
primesTo100 :: [Integer]
primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
-- powerMod
powerMod
powerMod m x n
where
f d a y = if d==0 then y
| otherwise = f
▲witns :: (Num a, Ord a, Random a) => Int -> a -> IO [a]
▲ g <- newStdGen
▲ then return $ take x $ randomRs (2,y-1) g
▲isMillerRabinPrime :: Integer -> IO Bool
▲isMillerRabinPrime n | even n = return (2 == n)
▲ | otherwise = do
▲ e = uncurry (++) . second(take 1) . span even . iterate (`div` 2) $ pn
Testing in GHCi:
<pre>*~> isMillerRabinPrime 4547337172376300111955330758342147474062293202868155909489
Line 1,215 ⟶ 1,226:
False
*~>
[907,911,919,929,937,941,947,953,967,971,977,983,991,997]</pre>
|