2014-12-19 38 views
3

我正在創建一個函數來分解haskell中的任何給定數字。所以我創造了這個:爲什麼我的素因子分解函數在結果中附加1?

primes :: [Integer] 
primes = 2:(sieve [3,5..]) 
    where 
     sieve (p:xs) = p : sieve [x |x <- xs, x `mod` ((p+1) `div` 2) > 0] 


factorize 2 = [2] 
factorize x 
    | divisible x = w:(factorize (x `div` w)) 
    | otherwise = [x] 
    where 
      divisible :: Integer -> Bool 
      divisible y = [x |x <- (2:[3,5..y]), y `mod` x == 0] /= [] 

      firstfactor :: Integer -> [Integer] -> Integer 
      firstfactor a (x:xs) 
       | a `ifdiv` x = x 
       | otherwise = firstfactor a xs 
      firstfactor a _ = a 

      ifdiv x y = mod x y == 0 

      w = firstfactor x primes 

功能工作正常,但追加1到列表的末尾,例如factorize 80會給這個名單:[2,2,2,2,5,1]我的問題是,爲什麼會出現這種情況?

+4

強制性鏈接到「Erathostenes篩」論文:http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf – Cactus 2014-12-19 01:36:44

回答

4

這是從代碼的兩部分來的。首先,factorize 1[1]。其次,由於x總是可以自行整除,所以你最後的呼叫將總是有w == x,所以遞歸將是w:(factorize (w `div` w)),這總是w:(factorize 1)

爲了解決這個問題,你可以添加一個額外的基本情況拋棄的因素的1

factorize 1 = [] 
factorize ... 

此外,您還可以,因爲它得到的,你已經擁有了otherwise情況納入降factorize 2 = [2]情況。

factorize 1 = []數學上有意義,因爲1 has no prime factors(記住1本身不是素數!)。這遵循與product [] = 1相同的邏輯 - 1是乘法的標識,當您無需乘法時,它將使其成爲「默認」值。

相關問題