-3
以下是我嘗試找到一些素數因子的代碼。我曾嘗試TAOCP算法轉換爲Haskell程序,但是當一些評估懶洋洋地或急切地我能理解:IO Monad懶惰地評價嗎?
modof2 n = let a0 = shiftR n 1
a1 = shiftL a0 1
in n-a1
iseven n = modof2 n == 0
factoringby2 n = let s=(lastf (takeWhile f [1..])) + 1
d=n `quot` powerof2 s
in (s,d)
where f s = let d = n `quot` (powerof2 s)
in if isodd d
then False
else True
lastf [] = 0
lastf xs = last xs
miller_rabin_prime_test n 0 result=return result
miller_rabin_prime_test n k result| (isodd n) && n>3 = do
a<-randomRIO(2,n-2)
let z = basic_step n a (fst sd) (snd sd)
miller_rabin_prime_test n (k-1) z
where sd=factoringby2 n
basic_step:: Integer->Integer->Int->Integer->Bool
basic_step n a s d =any (\x-> x==1 || x==n-1) (map x (map u [0..s-1]))
where u j=powerof2(j)*d
x j=modular_pow a j n 1
isprime n = if n==2 || n==3
then return True
else if n<2
then return False
else if iseven n
then return False
else miller_rabin_prime_test n 5 True
x_m :: Double->Integer->Integer
x_m 0 n = 2
x_m m n = f (x_m (m-1) n) `mod` n
where f x = x^2 +1
l::Double->Double
l m = 2^(floor (log2 m))
where log2 m = log m/log 2
g m n = let a = x_m m n
b = x_m ((l m)-1) n
in gcd (a-b) n
gg n = [g m n|m<-[1..]]
algorithmB n = do
testprime<-isprime n
let a = head (filter (1>) (gg n))
c<-algorithmB (n `div` a)
if testprime
then return []
else return (a:c)
algorithmB不會終止。爲什麼會發生?我認爲c<-algorithmB (n
是因爲它不懶惰評估。真的嗎? 謝謝div
a)
我試着去研究它,但是我無法運行你的代碼。它縮進了,缺少導入,未定義的符號和無意義的名字('l,g,gg')。如果您想獲得幫助,請至少提供可運行的代碼。 – rburny
爲什麼IO中的代碼呢?我沒有看到這個原因。 – sepp2k
@rburny你是不正確的。 '(>> =)''IO'在左邊參數中是嚴格的。然而,我懷疑無限遞歸是由遞歸的'算法B'沒有基本情況引起的。 – luqui